linux下c++连接mysql

发布于:2025-02-16 ⋅ 阅读:(133) ⋅ 点赞:(0)
1、下载mysql客户端使用的库文件

sudo apt install libmysqlclient-dev

头文件一般在 /usr/include/mysql/
库文件一般在 /usr/lib/x86_64-linux-gnu/

2、mysql c api开发者指南

>>>>官方连接

3、API使用实例
#include<mysql/mysql.h>
#include<errno.h>
#include<string.h>
#include<stdio.h>
int main(int argc, char *argv[])
{
    mysql_library_init(0,NULL,NULL);
    MYSQL mysql;
    mysql_init(&mysql);
 
    MYSQL * p_mysql =  mysql_real_connect(&mysql, 0/*ip/host*/
    , 0/*用户名*/, 0/*密码*/, 0/*数据库*/,0/*端口号*/, NULL, 0);
    if (nullptr == p_mysql)
    {
        printf("%d:%s\n",__LINE__,strerror(errno));
        return -1;
    }

    //插入数据
    if (0 > mysql_query(&mysql,"insert into single_table(key1,key2) values('123',444),('456',777)"))
    {
        printf("%d:%s\n",__LINE__,strerror(errno));
        return -1;
    }
    int affected = (int)mysql_affected_rows(&mysql);
    if (affected > 0)
        printf("修改了 %d 行数据\n",affected);
    else
    {
        printf("%d: %s",__LINE__,strerror(errno));
        return -1;
    }


    //查询数据
    if (0 > mysql_query(&mysql,"select * from single_table"))
    {
        printf("%d:%s\n",__LINE__,strerror(errno));
        return -1;
    }
    
    MYSQL_RES *res= mysql_store_result(&mysql);
    if (nullptr == res)
    {
       printf("%d:%s\n",__LINE__,strerror(errno));
       return -1;
    }
    MYSQL_ROW       row         = mysql_fetch_row(res);
    int             num_fields  = mysql_num_fields(res);
 
    printf("字段数:%d\n",num_fields);
    while (row != NULL)
    {
        //unsigned long * lengths     = mysql_fetch_lengths(res);
        //lengths是当前行各个字段的长度,如果lengths[i]==0,则row[i]==NULL
        for (int i = 0; i < num_fields; i++)
            printf("%s\t", row[i]);
        printf("\n");
        
        row = mysql_fetch_row(res);
    }
        
    mysql_free_result(res);
    mysql_close(&mysql);
    mysql_library_end();
    return 0;
}
4、编译

因为编译时需要使用mysql提供的共享库 libmysqlclient.so。默认情况下程序是找不到这个库的,以下提供两种方法:

  1. 将libmysqlclient.so拷贝到/usr/lib路径下
  2. 使用mysql_config --libs 命令生成共享库路径
gcc xxx.cpp `mysql_config --libs` -o xxx

``和$()的作用相同:将命令的输出当作返回值。


网站公告

今日签到

点亮在社区的每一天
去签到