首页 > 解决方案 > 如何将数据库服务器连接到 C 程序

问题描述

我在将名为northwind.sql 的数据库连接到我的C 程序时遇到了一些问题。我已经安装了: sudo apt install libmysqlclient-dev 并且也完成了gcc mysqlc.c `mysql_config --cflags --libs` . 当我尝试编译它时,它一直返回 NULL。我相信我的 makefile 可能有问题,但我可能错了。非常感谢任何建议或帮助。

这是我的代码和带有错误消息的文件:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <mysql/mysql.h>

void dberror(MYSQL *con)
{
    fprintf(stderr, "%s\n", mysql_error(con));
    mysql_close(con) ; exit(1);
}

int main(int argc, char *argv[])
{
    MYSQL *con;
    MYSQL_RES *result;
    MYSQL_ROW row;
    if((con=mysql_init(NULL)) == NULL)
    {
        dberror(con);
    }
    if(mysql_real_connect(con, "localhost", "cs4430", "cs4430", "northwind", 0, NULL, 0) == NULL) 
    {
        dberror(con);
    }
    if (mysql_query(con, "SELECT * FROM shippers")) 
    {
        dberror(con);
    }
    if ((result = mysql_store_result(con)) == NULL)
    {
        dberror(con);
    }
    int num_fields = mysql_num_fields(result);
    while ((row = mysql_fetch_row(result)))
    {
        for (int i = 0; i < num_fields; i++)
        {
            printf("%s, ", row[i]);
        }
        printf("\n");
    }
    mysql_free_result(result);
    mysql_close(con);
    exit(0);
}
main: mysqlc.c
    gcc -std=gnu11 -Werror -Wall -o mysqlc mysqlc.c -g
clean: main
    rm main
gcc -std=gnu11 -Werror -Wall -o mysqlc mysqlc.c -g
/usr/bin/ld: /tmp/cceuysEy.o: in function `dberror':
/home/unpocoloco/Documents/cs4430/A4/mysqlc.c:8: undefined reference to `mysql_error'
/usr/bin/ld: /home/unpocoloco/Documents/cs4430/A4/mysqlc.c:9: undefined reference to `mysql_close'
/usr/bin/ld: /tmp/cceuysEy.o: in function `main':
/home/unpocoloco/Documents/cs4430/A4/mysqlc.c:17: undefined reference to `mysql_init'
/usr/bin/ld: /home/unpocoloco/Documents/cs4430/A4/mysqlc.c:21: undefined reference to `mysql_real_connect'
/usr/bin/ld: /home/unpocoloco/Documents/cs4430/A4/mysqlc.c:25: undefined reference to `mysql_query'
/usr/bin/ld: /home/unpocoloco/Documents/cs4430/A4/mysqlc.c:29: undefined reference to `mysql_store_result'
/usr/bin/ld: /home/unpocoloco/Documents/cs4430/A4/mysqlc.c:33: undefined reference to `mysql_num_fields'
/usr/bin/ld: /home/unpocoloco/Documents/cs4430/A4/mysqlc.c:34: undefined reference to `mysql_fetch_row'
/usr/bin/ld: /home/unpocoloco/Documents/cs4430/A4/mysqlc.c:42: undefined reference to `mysql_free_result'
/usr/bin/ld: /home/unpocoloco/Documents/cs4430/A4/mysqlc.c:43: undefined reference to `mysql_close'
collect2: error: ld returned 1 exit status
make: *** [makefile:3: main] Error 1

标签: mysqlcdatabase

解决方案


推荐阅读