使用c语言连接mysql,需要使用mysql官网提供的库,可以在官网下载
准备工作:
保证mysql服务有效
官网下载合适的mysql connect库
也可以直接安装mysql服务
yum install -y mysql-devel
Connector/C使用
库格式如下:
[hb@MiWiFi-R1CL-srv lib]$ tree ..├── include│
├── big_endian.h
├── byte_order_generic.h├── byte_order_generic_x86.h├── decimal.h├── errmsg.h├── keycache.h├── little_endian.h├── m_ctype.h├── m_string.h├── my_alloc.h├── my_byteorder.h├── my_compiler.h├── my_config.h├── my_dbug.h├── my_dir.h├── my_getopt.h├── my_global.h├── my_list.h├── my_pthread.h├── mysql
├── client_authentication.h├── client_plugin.h├── client_plugin.h.pp├── get_password.h├── plugin_auth_common.h├── plugin_trace.h├── psi
├── mysql_file.h├── mysql_idle.h├── mysql_mdl.h├── mysql_memory.h├── mysql_ps.h├── mysql_socket.h├── mysql_sp.h
├── mysql_stage.h
├── mysql_statement.h├── mysql_table.h├── mysql_thread.h├── mysql_transaction.h├── psi_base.h├── psi.h└── psi_memory.h├── service_my_snprintf.h└── service_mysql_alloc.h├── mysql_com.h├── mysql_com_server.h├── mysqld_ername.h├── mysqld_error.h├── mysql_embed.h├── mysql.h├── mysql_time.h├── mysql_version.h├── my_sys.h├── my_xml.h├── sql_common.h├── sql_state.h├── sslopt-case.h├── sslopt-longopts.h├── sslopt-vars.h└── typelib.h└── lib├── libmysqlclient.a├── libmysqlclient_r.a -> libmysqlclient.a├── libmysqlclient_r.so -> libmysqlclient.so├── libmysqlclient_r.so.18 -> libmysqlclient.so.18├── libmysqlclient_r.so.18.3.0 -> libmysqlclient.so.18.3.0├── libmysqlclient.so -> libmysqlclient.so.18├── libmysqlclient.so.18 -> libmysqlclient.so.18.3.0└── libmysqlclient.so.18.3.0
其中inlcude包含所有的方法声明,lib包含所有的方法实现(打包成库)
尝试连接mysql client
通过mysql_get_client_info()函数,验证是否成功
#include <stdio.h>
#include <mysql.h>
int main(){printf("mysql client Version: %s\n", mysql_get_client_info());return 0;}[@MiWiFi-R1CL-srv lib]$ gcc -o test test.c -I./include -L./lib -lmysqlclient[@MiWiFi-R1CL-srv lib]$ lsinclude lib test test.c[@MiWiFi-R1CL-srv lib]$ ./test./test: error while loading shared libraries: libmysqlclient.so.18: cannot open
shared object file: No such file or directory
[@MiWiFi-R1CL-srv lib]$ export LD_LIBRARY_PATH=./lib #动态库查找路径,讲解ldd命令
[@MiWiFi-R1CL-srv lib]$ ./testmysql client Version: 6.1.6
至此引入库的工作已经做完,接下来是熟悉接口
接口介绍
初始化mysql_init()
要使用库,先进行初始化
MSYQL *mysql_init(MYSQL* mysql);
如:MYSQL* mfp = mysql_init(NULL)
连接数据库mysql_real_connect
初始化完毕后,必须先连接数据库,在进行后续操作(mysql网络部分是基于TCP/IP的)
MYSQL *mysql_real_connect(MYSQL *mysql, const char *host,const char *user,const char *passwd,const char *db,unsigned int port,const char *unix_socket,unsigned long clientflag);//建立好链接之后,获取英文没有问题,如果获取中文是乱码:
//设置链接的默认字符集是utf8,原始默认是latin1mysql_set_character_set(myfd, "utf8");
第一个参数MYSQL是C api中一个非常重要的变量(mysql_init的返回值),里面内存非常丰富,有port,dbname,charset等连接基本参数。也包含了一个叫st_mysql_methods的结构体变量,该变量里面保存着很多函数指针,这些函数指针将会在数据库连接成功后的各种数据操作中被调用
下发mysql命令mysql_query
int mysql_query(MYSQL* mysql, cost char* q);
第一个参数已经介绍过了,第二个参数为要执行的sql语句,如“select * from table”
获取执行结果mysql_store_result
sql执行完毕以后,如果是查询语句,还要读取数据,如果update,insert等语句,就看下操作成功与否。看看如何获取查询结果:如果mysql_query返回成功,就通过mysql_store_result函数读取结果,原型如下:
MYSQL_RES* mysql_store_result(MYSQL* mysql);
该函数会调用MYSQL变量中的st_mysql_methods中的read_rows函数指针获取查询的结果。同时该函数会返回MYSQL_RES这样一个变量,该变量用于保存查询的结果。同时该函数malloc了一片内存空间存储查询的数据,一定要记住free(result),不然肯定会造成内存泄露的。执行完mysql_store_result后,数据都在MYSQL_RES变量中了,下面的api基本就是读取MYSQL_RES的数据
这个结构是一个二维数组,每一行对应数据表的一条记录,一行每个数据对应每个字段
- 获取结果行数mysql_num_rows
my_ulonglong mysql_num_rows(MYSQL_RES* res);
- 获取结果列数mysql_num_fields
unsigned int mysql_num_fields(MYSQL_RES* res);
- 获取列名mysql_fetch_fields
MYSQL_FIELD* mysql_fetch_fields(MYSQL_RES* res);
如:
int fields = mysql_num_fields(res);MYSQL_FIELD *field = mysql_fetch_fields(res);int i = 0;for(; i < fields; i++){cout<<field[i].name<<" ";}cout<<endl;
- 获取结果内容mysql_fetch_row
MYSQL_ROW mysql_fetch_row(MYSQL_RES* result);
它会返回一个MYSQL_ROW变量,MYSQL_ROW其实就是char**,当成一个二维数组用
i = 0;MYSQL_ROW line;for(; i < nums; i++){line = mysql_fetch_row(res);int j = 0;for(; j < fields; j++){cout<<line[j]<<" ";}cout<<endl;}
- 关闭mysql连接mysql_close
另外,mysql C api还支持事务等常用操作
my_bool STDCALL mysql_autocommit(MYSQL * mysql, my_bool auto_mode);
my_bool STDCALL mysql_commit(MYSQL * mysql);
my_bool STDCALL mysql_rollback(MYSQL * mysql);
全
test.cpp
#include <iostream>
#include <mysql/mysql.h>
#include <unistd.h>using namespace std;
const char *host = "localhost";
const char *user = "connect";
const char *password = "1234";
const char *db = "con";
unsigned int port = 3306;int main()
{//printf("mysql client version: %s\n", mysql_get_client_info());MYSQL *my = mysql_init(nullptr);if (my == nullptr){cerr << "mysql init error" << endl;}if (mysql_real_connect(my, host, user, password, db, port, nullptr, 0) == nullptr){cerr << "mysql connect error" << endl;}mysql_set_character_set(my, "utf8");// const char *sql = "update person set name='zhangqiang' where id = 2";// const char *sql = "insert into person values(5, '李三', 18);";// const char *sql = "delete from person where id = 4";const char *sql = "select * from person";int n = mysql_query(my, sql);if (n == 0){cout << "success" << endl;}else{cout << "failed" << endl;return 3;}MYSQL_RES *res = mysql_store_result(my);if (res == nullptr){cerr << "result get error" << endl;return 4;}my_ulonglong rows = mysql_num_rows(res);my_ulonglong fields = mysql_num_fields(res);cout << rows << "行" << fields << "列" << endl;// 属性MYSQL_FIELD *field = mysql_fetch_field(res);for (int i = 0; i < fields; i++){cout << field[i].name << "\t\t";}cout << endl;// 获取结果内容for (int i = 0; i < rows; i++){// 迭代器功能MYSQL_ROW row = mysql_fetch_row(res);for (int j = 0; j < fields; j++){cout << row[j] << "\t\t";}cout << endl;}// sleep(10);cout << "connect success" << endl;mysql_free_result(res);mysql_close(my);return 0;
}
makefile
mytest: test.cppg++ -o mytest test.cpp -std=c++11 -L/lib64/mysql -lmysqlclient
.PHONY: clean
clean:rm -f *.o mytest