为了突出整个连接,查询数据库的流程,这里就不做函数返回值的判断了。详细的API参数信息可以去查MySQL的官方手册。
注:以下程序在VS2015下运行成功。
代码如下:
#include <stdio.h>
#include "mysql.h"
int main(void)
{
MYSQL mysql; //一个数据库结构体
MYSQL_RES* res; //一个结果集结构体
MYSQL_ROW row; //char** 二维数组,存放一条条记录
//初始化数据库
mysql_init(&mysql);
//设置编码方式
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "gbk");
//连接数据库
mysql_real_connect(&mysql, "localhost", "root", "root", "mfctest", 3306, NULL, 0);
//查询数据
mysql_query(&mysql, "select * from book where 书名 like '%C%'");
//获取结果集
res = mysql_store_result(&mysql);
//显示数据
printf("ID 书名 作者 出版社 出版时间 售价\n");
while (row = mysql_fetch_row(res))
{
printf("%s ", row[0]);
printf("%s ", row[1]);
printf("%s ", row[2]);
printf("%s ", row[3]);
printf("%s ", row[4]);
printf("%s \n", row[5]);
}
//释放结果集
mysql_free_result(res);
//关闭数据库
mysql_close(&mysql);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
结果如图:
注:如果出现乱码,请参见C语言查询数据库返回结果中文乱码