准备工作
- 参考资料中《安装基础MySQL环境》;
两个要点
- 头文件包含(解决编译问题)
#include <mysql/mysql.h>
包含该文件,需要提前安装mysql-devel包;
- 动态库链接(解决链接问题)
/usr/lib64/mysql/libmysqlclient.so
需要在gcc或makefile中指定该so的路径;
主要api接口
- MYSQL *mysql_init(MYSQL *mysql); - 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 client_flag); - int mysql_real_query(MYSQL *mysql, const char *query, unsigned long length); - MYSQL_RES *mysql_store_result(MYSQL *mysql) - MYSQL_ROW mysql_fetch_row(MYSQL_RES *result); - unsigned int mysql_num_fields(MYSQL_RES *result); - void mysql_close(MYSQL *mysql); - void mysql_free_result(MYSQL_RES *result);
demo测试代码及编译命令
- demo版测试代码如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <mysql/mysql.h> #define MAX_BUF_SIZE 2018 MYSQL *g_conn; MYSQL_RES *g_res; MYSQL_ROW g_row; const char *g_host_name = "localhost"; const char *g_user_name = "root"; const char *g_password = "Cyg26032583."; const char *g_db_name = "qxhgdfirstdb"; const unsigned int g_db_port = 3306; void print_mysql_error(const char *msg) { if (msg) printf("%s: %s\n", msg, mysql_error(g_conn)); else puts(mysql_error(g_conn)); } int execute_mysql(const char * sql) { if (mysql_real_query(g_conn, sql, strlen(sql))) return -1; return 0; } int init_mysql() { g_conn = mysql_init(NULL); if(!mysql_real_connect(g_conn, g_host_name, g_user_name, g_password, g_db_name, g_db_port, NULL, 0)) return -1; if (execute_mysql("set names utf8")) return -1; return 0; } int main(void) { int iNum_rows; int iNum_fields; if (init_mysql()); print_mysql_error(NULL); if (execute_mysql("insert into employeelst values(2,'chunmei'); ")) print_mysql_error(NULL); if (execute_mysql("SELECT * FROM employeelst;")) print_mysql_error(NULL); g_res = mysql_store_result(g_conn); iNum_rows = mysql_num_rows(g_res); iNum_fields = mysql_num_fields(g_res); printf("total %d records,each record %d datafields as follows:\n", iNum_rows, iNum_fields); printf("id\tname\n"); while ((g_row = mysql_fetch_row(g_res))) printf("%s\t%s\n", g_row[0], g_row[1]); mysql_free_result(g_res); mysql_close(g_conn); return 0; }
- 编译命令如下所示:
gcc mysql_test.c -L /usr/lib64/mysql -lmysqlclient
- 测试输出如下:
[qxhgd@localhost mysql]$ gcc mysql_test.c -L /usr/lib64/mysql -lmysqlclient;./a.out total 15 records,each record 2 datafields as follows: id name 1 秋香 9527 华安 2 chunmei
遇到问题及解决方式
- 问题1、fatal error: mysql/mysql.h: No such file or directory
## 编译报错打印 mysql_test.c:15:26: fatal error: mysql/mysql.h: No such file or directory #include <mysql/mysql.h> ^ compilation terminated. ## 解决方案 yum install mysql-devel
- 问题2、cannot find -lmysqlclient
## 编译报错打印 /usr/bin/ld: cannot find -lmysqlclient collect2: error: ld returned 1 exit status ## 解决方案 gcc mysql_test.c -L /usr/lib64/mysql -lmysqlclient