首先安装mysql,点完全安装,才能在在安装目录include找到相应的头文件,注意,是完全安装。
我装的是5.1版本,需要的头文件有
把需要的文件添加进去,然后再把 libmysql.lib放到项目目录里,文件在mysql安装目录 lib 下面.
#include "stdafx.h" #include <iostream> #include <winsock2.h> #include "mysql.h" //#pragma comment(lib, "ws2_32.lib") #pragma comment(lib,"libmysql.lib") using namespace std; int main(int argc, char* argv[]) { mysql_library_init(NULL,0,0); MYSQL mysql; mysql_init(&mysql); if(0==mysql_options(&mysql,MYSQL_SET_CHARSET_NAME,"utf8"))//设置字符集 { cout << "设置字符集成功\n\n" <<endl; } if(!mysql_real_connect(&mysql,"localhost","root","kwgkwg","test",0,NULL,CLIENT_MULTI_STATEMENTS))//连接数据库 { cout << "not connect mysql" << endl; }else { cout << "welcome to mysql\n\n\n"; } mysql_query(&mysql,"select * from demo1"); //执行SQL语句 MYSQL_RES *result=mysql_store_result(&mysql); //获取资源 int rowcount=mysql_num_rows(result); //获取记录数 unsigned int fieldcount=mysql_num_fields(result); //获取字段数 //cout << rowcount << endl; MYSQL_FIELD *field=NULL; //字段 MYSQL_ROW row=NULL; //记录 while(row=mysql_fetch_row(result)) { for(unsigned int i=0;i<fieldcount;i++) { field=mysql_fetch_field_direct(result,i); cout<<field->name<<":"<<row[i] <<"\n"; } } mysql_free_result(result); mysql_close(&mysql); mysql_server_end(); mysql_library_end(); return 0; }