在Visual Studio中编程访问MySQL数据库比较麻烦,因为需要导入MySQL提供的API,
不过知道了怎么操作之后也就简单了。主要是配置项目的编译环境。因为需要使用
mysql.h这个头文件,因此首先需要下载Windows下的MySQL源码包,下载地址如下
(选那个100多M的,10多M的只是源码,没有库):
http://www.mysql.com/downloads/cluster/
下载完解压,为了方便,我把解压后的文件内容都放到H:/MySQL目录下,这里你会看到
像include(头文件目录)和lib(库文件目录)。打开Visual Studio,新建工程后,开始
配置项目属性:
"工具->选项->项目和解决方案->VC++目录->显示一下内容的目录->包含文件"
在这里添加一行引用目录(当然也可以用绝对路径引用mysql.h):
H:/MySQL/include
"工具->选项->项目和解决方案->VC++目录->显示一下内容的目录->库文件"
在这里添加一行库目录(如果没有添加会出现“无法解析的外部符号 _mysql_init@4”之类的错误):
H:/MySQL/lib/debug
这个配置好了,还没完,在Visual Studio中还需要再文件前加一行:
#pragma comment(lib, "libmysql.lib")
表示使用库中的libmysql.lib库。
此外还需要添加winsock.h这个头文件,因为mysql_com.h的源码中要用到这个头文件。
之后就可以使用MySQL中API提供的数据库操作函数了。
事先已经在mysql的test数据库中添加了book表单:
+----+-----------------+--------+-------+
| ID | title | author | pages |
+----+-----------------+--------+-------+
| 1 | The Green Mile | 4 | 894 |
| 2 | Guards, Guards! | 2 | 302 |
| 3 | Imazdi | 3 | 354 |
| 4 | Gold | 1 | 405 |
| 5 | Howling Mad | 3 | 294 |
| 6 | Freedom | NULL | 230 |
+----+-----------------+--------+-------+
下面是一个来自MySQL权威指南的C语言使用API的例子
(注意用户名、密码、数据库名和表单名需要自己根据实际情况定义):
#include<stdio.h>
#include <WinSock.h>//这个必须有
#include"mysql.h"
#pragma comment(lib, "libmysql.lib") //VS中这个也必须有
int main(int argc, char* argv[])
{
MYSQL_RES *result;
MYSQL_ROW row;
MYSQL *connection,mysql;
int state;
/*connect MySQL database on localhost*/
mysql_init(&mysql);
connection = mysql_real_connect(&mysql,"localhost","username","userpw",
"test",0,0,0); //用户名 = username@localhost 密码 = userpw 数据库名 = test
/*check connection error*/
if(connection == NULL) {
printf(mysql_error(&mysql));
return 1;
}
state = mysql_query(connection,
"SELECT title, author FROM book"); //从book表单中查询title和author列
if(state != 0) {
printf(mysql_error(connection));
return 1;
}
/*must call mysql_store_result() before any other query*/
result = mysql_store_result(connection);
printf("Rows: %d/n",mysql_num_rows(result));
while((row = mysql_fetch_row(result)) != NULL ) {
printf("title: %s, author id: %s/n",
(row[0]?row[0]:"NULL"),
(row[1]?row[1]:"NULL"));
}
/*release result set*/
mysql_free_result(result);
/*close connection*/
mysql_close(connection);
printf("Done./n");
return 0;
}
下面是运行结果:
Rows: 6
title: The Green Mile, author id: 4
title: Guards, Guards!, author id:
title: Imazdi, author id: 3
title: Gold, author id: 1
title: Howling Mad, author id: 3
title: Freedom, author id: NULL
Done.
请按任意键继续. . .