使用C语言连接mysql

操作系统 win11
CMakerLists.txt文件配置如下:

cmake_minimum_required(VERSION 3.19)
project(HanNuo C)
set(CMAKE_C_STANDARD 99)
add_executable(HanNuo main.c SuanFa.c SuanFa.c)

include_directories(D:\\develop\\MySQL\ Server\ 8.0\\include)#include目录
link_directories(D:\\develop\\MySQL\ Server\ 8.0\\lib)#lib目录
link_libraries(libmysql)  #lib下dll文件名
#add_executable(HanNuo main.c)
target_link_libraries(HanNuo libmysql.lib)

数据库连接代码:

int SqlIni(){
    //char sql[] = {};
    MYSQL mysql_con;
    if(mysql_init(&mysql_con)==NULL)
    {
        printf("mysql init err\n");
        exit(1);
    }
    if(mysql_real_connect(&mysql_con,"localhost","root","admin","test1",3306,0,0)==NULL){
        printf("connect err\n");
    }
    else{
        printf("connect success\n");
    }
    char* sql="select * from user";
    if(mysql_query(&mysql_con,sql)!=0)
    {
        printf("query sql err\n");
    }
    mysql_close(&mysql_con);
}

编译后报错:
CMakeFiles\HanNuo.dir/objects.a(main.c.obj): In function SqlIni': D:/Test/HanNuo/main.c:44: undefined reference to mysql_init’
D:/Test/HanNuo/main.c:49: undefined reference to mysql_real_connect' D:/Test/HanNuo/main.c:56: undefined reference to mysql_query’
D:/Test/HanNuo/main.c:60: undefined reference to `mysql_close’
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\HanNuo.dir\build.make:105: HanNuo.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:94: CMakeFiles/HanNuo.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:101: CMakeFiles/HanNuo.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:136: HanNuo] Error 2

然后我将CmakerLists文件改为:

cmake_minimum_required(VERSION 3.19)
project(HanNuo C)
set(CMAKE_C_STANDARD 99)
#add_executable(HanNuo main.c SuanFa.c SuanFa.c)

include_directories(D:\\develop\\MySQL\ Server\ 8.0\\include)#include目录
link_directories(D:\\develop\\MySQL\ Server\ 8.0\\lib)#lib目录
link_libraries(libmysql)  #lib下dll文件名
add_executable(HanNuo main.c)
target_link_libraries(HanNuo libmysql.lib)

虽然项目可以编译了(可能是我上面的连接了其他文件的缘故吧),但是运行程序发现没有任何输出。于是我又一行一行测试,直到代码运行到mysql_init的时候就停止了。然后我就各种网上找有没有人遇到类似的情况,试过很多次都无效。后来我把libmysql.dll文件复制到exe文件目录下奇迹发生了,终于解决了困扰我几天的问题!!!

你可能感兴趣的:(C,mysql,c语言,数据库)