C Connect to MySQL8

Linux installation MySQL 8

Please refer to the article: Detailed explanation of Docker installation MySQL 8

Visual Studio 2022 writes C to connect to MySQL 8

C source code

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

int main(void)
{
    MYSQL mysql;    //数据库句柄
    MYSQL_RES* res; //查询结果集
    MYSQL_ROW row;  //记录结构体

    //初始化数据库
    mysql_init(&mysql);

    //设置字符编码
    mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "gbk");

    //连接数据库
    if (mysql_real_connect(&mysql, "192.168.43.10", "root", "123456", "bill", 3306, NULL, 0) == NULL) {
        printf("错误原因: %s\n", mysql_error(&mysql));
        printf("连接失败!\n");
        exit(-1);
    }

    //查询数据
    int ret = mysql_query(&mysql, "select * from base_building;");
    printf("ret: %d\n", ret);

    //获取结果集
    res = mysql_store_result(&mysql);

    //给ROW赋值,判断ROW是否为空,不为空就打印数据。
    while (row = mysql_fetch_row(res))
    {
        printf("%s  ", row[0]);  //打印ID
        printf("%s  ", row[1]);  //打印班级
        printf("%s  ", row[2]);  //打印姓名
    }
    //释放结果集
    mysql_free_result(res);

    //关闭数据库
    mysql_close(&mysql);

    system("pause");
    return 0;
}

Show results 

project configuration

Step 1: Click VC++ Project -> Properties, in the include directory, add the path to the include file in the mysql installation file here.

 Step 2: In the linker on the property page, click "Input" and add the libmysql.lib file in the lib directory in the mysql installation folder to "Additional Dependencies". Note that the dependency libmysql.lib is directly added here. Just add the name, don't add the path.

 

 Step 3: Copy lib\libmysql.dll in the mysql installation directory to c:\windows\system32

Guess you like

Origin blog.csdn.net/zhouzhiwengang/article/details/132448666