c++访问mysql数据库
首先,把mysql目录下的include放到项目目录下,然后把libmysql.lib和libmysql.dll放到debug目录下。
#include<mysql.h>之前一定要加上#include<windows.h>否则会产生编译错误。
#include "stdafx.h"
#include <Windows.h>
#include
"include\mysql.h"
#include <iostream>
using namespace
std;
#pragma comment(lib,"libmysql.lib")
int _tmain(int argc,
_TCHAR* argv[])
{
MYSQL mysql;
MYSQL_RES *result=NULL;
MYSQL_FIELD
*fd;
MYSQL_ROW sql_row;
int
res;
mysql_init(&mysql);
if(!mysql_real_connect(&mysql,"172.1.1.1","root","123456","mysql",3306,0,0))
{
fprintf(stderr,"Failedtoconnecttodatabase:Error:%s\\n",mysql_error(&mysql));
}else{
mysql_query(&mysql,"SET NAMES GBK");//设置编码格式,否则在cmd下无法显示中文
res=mysql_query(&mysql,"select * from
help_category");//不等于0表示出错
if(!res){
result=mysql_store_result(&mysql);
if(result){
int i=0,j;
cout<<"number of result: "<<(unsigned
long)mysql_num_rows(result)<<endl;//获取行号
j=mysql_num_fields(result);//获取列数
for(i=0;i<j;i++)
{
fd=mysql_fetch_field(result);//获取列名
cout<<fd->name<<"\t";
}
cout<<endl;
while(sql_row=mysql_fetch_row(result)){//获取每行数据
for(i=0;i<j;i++)
{
if(NULL!=sql_row[i])
//防止数据为空
cout<<sql_row[i]<<"\t";
}
cout<<endl;
}
}
}else{
cout<<"query sql failed!"<<endl;
}
}
if(result!=NULL){
mysql_free_result(result);//释放结果资源
}
mysql_close(&mysql);//断开连接
system("pause");
return 0;
}