#include <windows.h>
#include <iostream>
#include <mysql.h>
#include <stdio.h>
using namespace std;
int main()
{
//connection params
char *host = "localhost";
char *user = "root";
char *pass = "123456";
char *db = "movee";
//sock
MYSQL *sock;
MYSQL_RES *results;
MYSQL_ROW record;
sock = mysql_init(0);
if (sock) cout << "sock handle ok!" << endl;
else {
cout << "sock handle failed!" << mysql_error(sock) << endl;
}
//connection
if (mysql_real_connect(sock, host, user, pass, db, 0, NULL, 0))
cout << "connection ok!" << endl;
else {
cout << "connection fail: " << mysql_error(sock) << endl;
}
mysql_set_character_set(sock,"gb2312");
//connection character set
cout << "connection character set: " << mysql_character_set_name(sock) << endl;
//wait for posibility to check system/mysql sockets
if(mysql_query(sock,"select * from admin_user"))
{
cout<<"very good!"<<endl;
}
results=mysql_store_result(sock);
printf("用户名\t等级\n");
while(record=mysql_fetch_row(results))
{
printf("%s\t%s \n",record[1],record[3]);
}
mysql_free_result(results);
system("PAUSE");
//closing connection
mysql_close(sock);
return EXIT_SUCCESS;
}
我的mysql安装路径为d:\software\mysql5.0
所以要在VC中设置include路径和lib的路径。
(1)添加MySql的include目录到VC工作台中
Project->Settings->C/C++->Category->Preprocessor->Additional include directories中添加:D:\software\mysql5.0\include。
添加lib的路径:Tools->Options->Directories中选择Library files,然后添加lib的目录:D:\SOFTWARE\MYSQL5.0\LIB
(2)在Project->Settings->Link中,添加libmysql.lib到Object/libray modules中。
(3)确保Project Options中为/subsystem:console而不是/subsystem:window,否则编译错误。