并非全部原创,我也是刚刚接触,感觉有用,发出来给其他需要的人看看,原文里面有些有错误,做了一些修改,并加了一些提示
1.把安装好的MySQL目录里的libmySQL.dll复制到C:\Windows\system32\下,
添加路径:project->property->linker->general->Additional library directories 填写lib路径,即system32;
2.把MySQL的头文件添加到环境中:![](http://www.2cto.com/uploadfile/2012/0517/20120517023057468.jpg)
3.把libmysql.lib添加到VS 2010的项目中。
![](http://www.2cto.com/uploadfile/2012/0517/20120517023057240.jpg)
4.示例代码:
[cpp] *
* 文件名:mysql.c *
* *
* 功能:连接MySQL并查询 *
* *
**********************************************/
#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h> //Socket,连接MySQL也需要用的 这个头文件一定要在下一个头文件之前,要不然编译不能通过!!
MYSQL mysql, *sock; //声明MySQL的句柄
int main(void)
{
const char * host = "127.0.0.1"; //因为是作为本机测试,所以填写的是本地IP
const char * user = "root"; //这里改为你的用户名,即连接MySQL的用户名
const char * passwd = "123456"; //这里改为你的用户密码
const char * db = "test"; //这里改为你要连接的数据库的名字
unsigned int port = 3306; //这是MySQL的服务器的端口,如果你没有修改过的话就是3306。
const char * unix_socket = NULL; //unix_socket这是unix下的,我在Windows下,所以就把它设置为NULL
unsigned long client_flag = 0; //这个参数一般为0
const char * i_query = "select * from student"; //查询语句 注意这里有表名
MYSQL_RES * result; //保存结果集的 www.2cto.com
MYSQL_ROW row; //代表的是结果集中的一行
mysql_init(&mysql); //连接之前必须使用这个函数来初始化
if ( (sock = mysql_real_connect(&mysql, host, user, passwd, db, port, unix_socket, client_flag) ) == NULL ) //连接MySQL
{
printf("连接失败,原因是: \n");
fprintf(stderr, " %s\n", mysql_error(&mysql));
exit(1);
}
else
{
fprintf(stderr, "连接MySQL成功!!\n");
}
if ( mysql_query(&mysql, i_query) != 0 ) //如果连接成功,则开始查询
{
fprintf(stderr, "查询失败!\n");
exit(1);
}
else
{
if ( (result = mysql_store_result(&mysql)) == NULL ) //保存查询的结果
{
fprintf(stderr, "保存结果集失败!\n");
exit(1);
}
else
{
while ( (row = mysql_fetch_row(result)) != NULL ) //读取结果集中的数据,返回的是下一行。因为保存结果集时,当前的游标在第一行【之前】
{
printf("name is %s\t", row[0]); //打印当前行的第一列的数据
printf("age is %s\t\n", row[1]); //打印当前行的第二列的数据
}
}
}
mysql_free_result(result); //释放结果集
mysql_close(sock); //关闭连接
system("pause");
exit(EXIT_SUCCESS);
}
这个是我的数据库的内容:
这个是输出的结果