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 基础代码,封装通用表增删改查操作。

待补充

相关推荐
伏虎山真人18 分钟前
开源数据库 - mysql - mysql-server-8.4(gtid主主同步+ keepalived热切换)部署方案
数据库·mysql·开源
FIN技术铺3 小时前
Redis集群模式之Redis Sentinel vs. Redis Cluster
数据库·redis·sentinel
lb36363636363 小时前
介绍一下数组(c基础)(详细版)
c语言
内核程序员kevin4 小时前
在Linux环境下使用Docker打包和发布.NET程序并配合MySQL部署
linux·mysql·docker·.net
CodingBrother4 小时前
MySQL 中的 `IN`、`EXISTS` 区别与性能分析
数据库·mysql
kayotin4 小时前
Wordpress博客配置2024
linux·mysql·docker
一丝晨光5 小时前
编译器、IDE对C/C++新标准的支持
c语言·开发语言·c++·ide·msvc·visual studio·gcc
代码小鑫5 小时前
A027-基于Spring Boot的农事管理系统
java·开发语言·数据库·spring boot·后端·毕业设计
小小不董5 小时前
Oracle OCP认证考试考点详解082系列16
linux·运维·服务器·数据库·oracle·dba
甄臻9245 小时前
Windows下mysql数据库备份策略
数据库·mysql