C 语言连接MySQL 数据库

前提条件

本机安装MySQL 8 数据库

整体步骤

第一步:开启Windows 子系统安装Ubuntu 22.04.4,安装MySQL 数据库第三方库执行 如下命令:

sudo aptitude install libmysqlclient-dev

wz2012@LAPTOP-8R0KHL88:/mnt/e/vsCode/cpro$ sudo aptitude install libmysqlclient-dev
The following NEW packages will be installed:
  libmysqlclient-dev libmysqlclient21{a} libssl-dev{a} libzstd-dev{a} zlib1g-dev{a}
The following packages will be REMOVED:
  libssl1.1{u}
0 packages upgraded, 5 newly installed, 1 to remove and 10 not upgraded.
Need to get 5901 kB of archives. After unpacking 26.2 MB will be used.
Do you want to continue? [Y/n/?] y
Get: 1 http://mirrors.aliyun.com/ubuntu jammy-security/main amd64 libmysqlclient21 amd64 8.0.37-0ubuntu0.22.04.3 [1302 kB]
Get: 2 http://mirrors.aliyun.com/ubuntu jammy-security/main amd64 libssl-dev amd64 3.0.2-0ubuntu1.15 [2376 kB]
Get: 3 http://mirrors.aliyun.com/ubuntu jammy/main amd64 libzstd-dev amd64 1.4.8+dfsg-3build1 [401 kB]
Get: 4 http://mirrors.aliyun.com/ubuntu jammy-security/main amd64 zlib1g-dev amd64 1:1.2.11.dfsg-2ubuntu9.2 [164 kB]
Get: 5 http://mirrors.aliyun.com/ubuntu jammy-security/main amd64 libmysqlclient-dev amd64 8.0.37-0ubuntu0.22.04.3 [1658 kB]
Fetched 5901 kB in 22s (271 kB/s)
(Reading database ... 32533 files and directories currently installed.)
Removing libssl1.1:amd64 (1.1.1f-1ubuntu2.22) ...
Selecting previously unselected package libmysqlclient21:amd64.
(Reading database ... 32523 files and directories currently installed.)
Preparing to unpack .../libmysqlclient21_8.0.37-0ubuntu0.22.04.3_amd64.deb ...
Unpacking libmysqlclient21:amd64 (8.0.37-0ubuntu0.22.04.3) ...
Selecting previously unselected package libssl-dev:amd64.
Preparing to unpack .../libssl-dev_3.0.2-0ubuntu1.15_amd64.deb ...
Unpacking libssl-dev:amd64 (3.0.2-0ubuntu1.15) ...
Selecting previously unselected package libzstd-dev:amd64.
Preparing to unpack .../libzstd-dev_1.4.8+dfsg-3build1_amd64.deb ...
Unpacking libzstd-dev:amd64 (1.4.8+dfsg-3build1) ...
Selecting previously unselected package zlib1g-dev:amd64.
Preparing to unpack .../zlib1g-dev_1%3a1.2.11.dfsg-2ubuntu9.2_amd64.deb ...
Unpacking zlib1g-dev:amd64 (1:1.2.11.dfsg-2ubuntu9.2) ...
Selecting previously unselected package libmysqlclient-dev.
Preparing to unpack .../libmysqlclient-dev_8.0.37-0ubuntu0.22.04.3_amd64.deb ...
Unpacking libmysqlclient-dev (8.0.37-0ubuntu0.22.04.3) ...
Setting up libmysqlclient21:amd64 (8.0.37-0ubuntu0.22.04.3) ...
Setting up libzstd-dev:amd64 (1.4.8+dfsg-3build1) ...
Setting up libssl-dev:amd64 (3.0.2-0ubuntu1.15) ...
Setting up zlib1g-dev:amd64 (1:1.2.11.dfsg-2ubuntu9.2) ...
Setting up libmysqlclient-dev (8.0.37-0ubuntu0.22.04.3) ...
Processing triggers for man-db (2.10.2-1) ...
Processing triggers for libc-bin (2.35-0ubuntu3.8) ...

第二步:编写MySQL 8 数据库连接,验证数据是否能够正常联通。

温馨提示:相关重要说明,已经代码中进行标记。

mysql_demo.c

#include <mysql/mysql.h>
#include <stdio.h>
// MySQL 数据库连接
int main(void){
    // 数据库连接
    MYSQL *conn;
    // 数据库集合
    MYSQL_RES *res;
    // 数据库行记录
    MYSQL_ROW *row;


    char *server = "localhost";
    char *user = "root";
    char *password = "123456"; /* 此处改成你的密码 */
    char *database = "base";/*数据库,比如base*/

    conn = mysql_init(NULL);
 
   /* 数据库连接 */
   if (!mysql_real_connect(conn, server,
          user, password, database, 0, NULL, 0)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   printf("数据库连接成功");

    return 0;

}

第三步:编译mysql_demo.c文件

我这里演示错误的编译方式/(使用常用代码编辑方式,这是一种错误方式)错误结果如下:

wz2012@LAPTOP-8R0KHL88:/mnt/e/ubuntu_code$ cd "/mnt/e/ubuntu_code/" && gcc mysql_demo.c -o mysql_demo && "/mnt/e/ubuntu_code/"mysql_demo
/usr/bin/ld: /tmp/ccm7ZrUH.o: in function `main':
mysql_demo.c:(.text+0x3e): undefined reference to `mysql_init'
/usr/bin/ld: mysql_demo.c:(.text+0x6b): undefined reference to `mysql_real_connect'
/usr/bin/ld: mysql_demo.c:(.text+0x80): undefined reference to `mysql_error'
collect2: error: ld returned 1 exit status

上述代码错误原因:没有找到mysql_init 函数定义的库文件/undefined reference to `mysql_init'。

解决办法:

使用mysql_config 命令查找MySQL 依赖的LIB库, --libs_r 就是我们需要添加编译mysql 库链接参数。

wz2012@LAPTOP-8R0KHL88:/mnt/e/ubuntu_code$ mysql_config
Usage: /usr/bin/mysql_config [OPTIONS]
Compiler: GNU 11.4.0
Options:
        --cflags         [-I/usr/include/mysql ]
        --cxxflags       [-I/usr/include/mysql ]
        --include        [-I/usr/include/mysql]
        --libs           [-L/usr/lib/x86_64-linux-gnu -lmysqlclient -lzstd -lssl -lcrypto -lresolv -lm]
        --libs_r         [-L/usr/lib/x86_64-linux-gnu -lmysqlclient -lzstd -lssl -lcrypto -lresolv -lm]
        --plugindir      [/usr/lib/mysql/plugin]
        --socket         [/var/run/mysqld/mysqld.sock]
        --port           [0]
        --version        [8.0.37]
        --variable=VAR   VAR is one of:
                pkgincludedir [/usr/include/mysql]
                pkglibdir     [/usr/lib/x86_64-linux-gnu]
                plugindir     [/usr/lib/mysql/plugin] 

切换至Unbuntu 命令输出控制台输入如下编译指令:

wz2012@LAPTOP-8R0KHL88:/mnt/e/ubuntu_code$ gcc mysql_demo.c -o mysql_demo -L/usr/lib/x86_64-linux-gnu -lmysqlclient -lzstd -lssl -lcrypto -lresolv -lm

第四步:测试MySQL 数据库是否联通,遇到的问题总结

1、问题1:基于localhost 无法联通MySQL 服务器,提示错写信息为:

wz2012@LAPTOP-8R0KHL88:/mnt/e/ubuntu_code$ ./mysql_demo

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (13)

解决办法:将localhost 修改为127.0.0.1

2、问题2:针对问题1,将windows 访问地址由localhost 修改 为127.0.0.1 ,提示的错误信息为:

wz2012@LAPTOP-8R0KHL88:/mnt/e/ubuntu_code$ ./mysql_demo

Can't connect to MySQL server on '127.0.0.1:3306' (111)

解决办法:将localhost 修改为本机IP地址(在window 系统上使用ipconf命令查看本机IP地址)

3、问题3:针对问题2,将mysql 访问地址由127.0.0.1 修改为192.168.43.1, 提升的错误信息为:

wz2012@LAPTOP-8R0KHL88:/mnt/e/ubuntu_code$ ./mysql_demo

Access denied for user 'root'@'LAPTOP-8R0KHL88' (using password: YES)

4、针对问题3 主要是由于MySQL 服务访问权限设置问题造成。

在MySQL 控制台执行如下命令:

use mysql;

update user set Host='%' where User ='root';

FLUSH PRIVILEGES;

第五步: 基于MySQL 联通代码,打印指定数据库所有表名:

#include <mysql/mysql.h>
#include <stdio.h>
// MySQL 数据库连接
int main(void){
    // 数据库连接
    MYSQL *conn;
    // 数据库集合
    MYSQL_RES *res;
    // 数据库行记录
    MYSQL_ROW row;


    char *server = "192.168.43.1";
    char *user = "root";
    char *password = "123456"; /* 此处改成你的密码 */
    char *database = "base";/*数据库,比如base*/

    conn = mysql_init(NULL);
 
   /* 数据库连接 */
   if (!mysql_real_connect(conn, server,
          user, password, database, 0, NULL, 0)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

     /*SQL 查询 */
   if (mysql_query(conn, "show tables")) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }
 
    res = mysql_use_result(conn);
 
   /* 输出表名 */
   printf("MySQL Tables in mysql database:\n");
   while ((row = mysql_fetch_row(res)) != NULL)
      printf("%s \n", row[0]);
 
   /* 关闭数据库连接 */
    mysql_free_result(res);
    mysql_close(conn);

    return 0;

}

结果输出:

wz2012@LAPTOP-8R0KHL88:/mnt/e/ubuntu_code$ ./mysql_demo
MySQL Tables in mysql database:
base_user
bds_building
bds_building_progress
bds_contract
bds_contract_entity
bds_contract_house
bds_enterprise_org
bds_house
bds_house_flag
bds_license
bds_license_house
bds_project
bds_subs_contract
bds_subs_contract_entity
bds_subs_contract_house
bds_yw_wqba
gethouse

第六步: 基于MySQL 基础代码,封装通用表增删改查操作。

待补充

相关推荐
yangfeipancc23 分钟前
数据库-用户管理
android·数据库
fen_fen2 小时前
mysql,mariadb,postgresql创建用户和授权的命令
mysql·postgresql·mariadb
两点王爷2 小时前
Java读取csv文件内容,保存到sqlite数据库中
java·数据库·sqlite·csv
凡人的AI工具箱3 小时前
每天40分玩转Django:Django部署概述
开发语言·数据库·后端·python·django
技术路上的苦行僧4 小时前
分布式专题(9)之Mysql高可用方案
分布式·mysql·mgr·mha·mysql高可用·mmm
2401_871213304 小时前
mysql之MHA
数据库·mysql
言之。4 小时前
【MySQL】事务
数据库·mysql
潇湘秦4 小时前
Oracle 11G还有新BUG?ORACLE 表空间迷案!
数据库·oracle
落霞与孤鹭齐飞。。4 小时前
学生考勤系统|Java|SSM|VUE| 前后端分离
java·mysql·毕业设计·课程设计
凡人的AI工具箱5 小时前
每天40分玩转Django:Django Email
数据库·人工智能·后端·python·django·sqlite