Linux下C连接MySQL数据库

时间:2023-01-24 11:28:33

Linux下C连接MySQL数据库

自己的例子:

要连接数据库名称是hhh,用户名是tom,连接的数据表是 data_import,其中 data_import数据结构如下(5个属性):

[root@localhost cProject]# cat c_mysql.c
#include <mysql/mysql.h>
#include <stdlib.h>
#include <stdio.h>

void main()
{
        MYSQL *mysql;
        MYSQL_RES *res;
        MYSQL_ROW row;
        char *query = "select * from data_import;";
        int t,r;
        mysql_init(mysql);

        if (!mysql_real_connect(
                                mysql,"localhost","tom","123","hhh",0,NULL ,0))//连接到Mysql服务器
        {
                printf("Error connecting to database:%s\n",mysql_error(mysql));
        }
        else
                printf("Connected to database successfully!\n");
        t = mysql_query(mysql,query);

        if (t)
        {
                printf("Error making query:%s\n",mysql_error(mysql));
        }
        else
        {
                printf("Query successfully!\n");
                res = mysql_use_result(mysql);//获得逐行的结果集检索
                if (res)
                {
                        for(r=0;r<=mysql_field_count(mysql);r++)//mysql_field_count()返回上次执行语句的结果列的数目
                        {
                                row = mysql_fetch_row(res);//从结果集中获得下一行
                                if (row < 0) break;
                                for(t=0;t<mysql_num_fields(res);t++)//mysql_num_fields() 返回结果集中的列数
                                        printf("%s ",row[t]);
                                printf("\n");
                        }
                }
                mysql_free_result(res);//释放结果集使用的内存
        }
        mysql_close(mysql);//关闭服务器连接
}


编译:
Linux下C连接MySQL数据库

执行(部分结果):

[root@localhost cProject]# ./c_mysql
Connected to database successfully!
Query successfully!
  TOM 24 Beijing football
  TOM 24 Beijing football
  LIU 27 heibei football
  JIM 26 shandong football
  HAN 28 beijing football
  MENG 25 Beijing tennis

网上看到的另一个例子:

#include<stdlib.h>   
#include<stdio.h>   
#include<mysql.h>   
   
int main(int argc,char* argv[])   
{   
    MYSQL *conn_ptr;   
   
    conn_ptr = mysql_init(NULL);   
    if(!conn_ptr){   
        fprintf(stderr,"mysql_init failed\n");   
        return EXIT_FAILURE;   
    }      
   
    conn_ptr = mysql_real_connect( conn_ptr, "localhost", "li", "li","mysql", 0, NULL, 0 );   
   
    if(conn_ptr){   
        printf("Connection success\n");   
    }else{   
        printf( "Connection failed\n");   
    }      
   
    mysql_close( conn_ptr );   
   
    return 0;   
}  


编译方法:


gcc $(mysql_config --cflags) xxx.c -o xxx $(mysql_config --libs)


方法二:gcc test.c -o test -L/user/lib/mysql -lmysqlclient                成功!


方法三:gcc test.c -o test $(mysql_config --cflags) $(mysql_config --libs)


或者:gcc test.c -o test $(mysql_config --cflags --libs)                        成功!




自己实验时只有方法2成功了。