Linux下C访问MySQL

前几天Windows下安装了下mysql,然后编译了一个C程序访问mysql数据库,结果都无法连上,原因未知,同样的source code直接copy到CentOS上来试试

1:安装mysql

sudo yum install mysql mysql-devel mysql-server

然后直接通过service来启动

sudo service mysqld start

2:编译运行

直接将windows上执行那程序copy到linux,改下端口和数据库名字,由于没重新创建,就用mysql自带的test数据库做下测试

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

int main(){
        MYSQL *conn_ptr;

        conn_ptr = mysql_init(NULL);
        if (!conn_ptr){
                printf("mysql_init failed\n");
                exit(0);
        }
        conn_ptr = mysql_real_connect(conn_ptr, "localhost", "root", "", "test", 0, NULL, 0);

        if (conn_ptr)
                printf("Connection successful!\n");
        else
                printf("Connection failed\n");

        mysql_close(conn_ptr);
        return 0;
}

[root@localhost lihui]# gcc mysql.c -lmysqlclient
/usr/local/bin/ld: cannot find -lmysqlclient
collect2: error: ld returned 1 exit status

报了一个错误,连接不上库,直接搜索一下

[root@localhost lihui]# locate libmysqlclient.so
/usr/lib64/mysql/libmysqlclient.so
/usr/lib64/mysql/libmysqlclient.so.16
/usr/lib64/mysql/libmysqlclient.so.16.0.0

看了下系统LIB的PATH

[root@localhost lihui]# echo $LD_LIBRARY_PATH
/usr/local/lib:/usr/lib64:/usr/lib

这里就偷个懒直接把动态库copy到系统能找到的地方

[root@localhost lihui]# cp /usr/lib64/mysql/libmysqlclient.so /usr/lib64/

编译运行

[root@localhost lihui]# gcc mysql.c -lmysqlclient
[root@localhost lihui]# ./a.out 
Connection successful!

可见Linux下已经OK,Windows下还是配置或者权限问题~!

发表评论