当前位置:Gxlcms > mysql > c++访问mysql数据库

c++访问mysql数据库

时间:2021-07-01 10:21:17 帮助过:8人阅读

首先,把mysql目录下的include放到项目目录下,然后把libmysql.lib和libmysql.dll放到debug目录下。

#include之前一定要加上#include否则会产生编译错误。

#include "stdafx.h"
#include
#include "include/mysql.h"
#include
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)<
j=mysql_num_fields(result);//获取列数
for(i=0;i {
fd=mysql_fetch_field(result);//获取列名
cout<name<<"/t";
}
cout< while(sql_row=mysql_fetch_row(result)){//获取每行数据
for(i=0;i {
if(NULL!=sql_row[i])//防止数据为空
cout< }
cout< }
}
}else{
cout<<"query sql failed!"< }
}
if(result!=NULL){
mysql_free_result(result);//释放结果资源
}
mysql_close(&mysql);//断开连接
system("pause");
return 0;
}

人气教程排行