用于使用C++连接MySql的朋友。
只是一个简单的封装,没有大规模测试过,自用暂未发现问题。
PS:我C++环境是VS2010
DBUtil.h
#pragma once
#include "winsock.h"
#include <mysql.h>
#include <iostream>
#include <string>
using namespace std;
class DBUtil
{
private:
MYSQL mydata;
MYSQL_RES *results;
public:
DBUtil(void);
virtual ~DBUtil(void);
bool executeSql(string sql);
MYSQL_RES* querySql(string sql);
};
DBUtil.cpp
#include "StdAfx.h"
#include "winsock.h"
#include <mysql.h>
#include <iostream>
#include <string>
#include "DBUtil.h"
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "libmysql.lib")
using namespace std;
DBUtil::DBUtil(void)
{
//初始化MySQL C API库
mysql_library_init(0,NULL,NULL);
//初始化mydata的数据结构,mydata是MYSQL对象
mysql_init(&mydata);
//连接选项:添加GBK字符集支
mysql_options(&mydata,MYSQL_SET_CHARSET_NAME,"gbk");
//连接数据库
//这儿换上自己的MySql配置
//mysql_real_connect(&mydata,"服务器地址","用户名","密码","数据库名","端口",0,0)
if(mysql_real_connect(&mydata,"localhost","root","admin","db_test",3306,0,0)==NULL) {
cout<<"数据库连接错误"<<endl;
system("exit");
}
}
DBUtil::~DBUtil(void)
{
//关闭数据库
mysql_close(&mydata);
mysql_library_end();
}
//executeSql用于执行语句,像insert,update,drop等
bool DBUtil::executeSql(string sql) {
bool sqlFlag=false;
char sqlText[500]="";
//string转*char
strcpy_s(sqlText,sql.c_str());
//执行sql语句
if(mysql_query(&mydata,sqlText)==0) {
sqlFlag=true;
}
else {
cout<<"sql语句执行错误"<<endl;
return sqlFlag;
}
return sqlFlag;
}
//querySql用于执行查询语句
MYSQL_RES* DBUtil::querySql(string sql) {
char sqlText[500]="";
//string转*char
strcpy_s(sqlText,sql.c_str());
//执行sql语句
if(mysql_query(&mydata,sqlText)==1) {
cout<<"sql语句执行错误"<<endl;
}
results = mysql_store_result(&mydata);
return results;
}
执行Sql语句(executeSql)的程序示例
#include "stdafx.h"
#include <iostream>
#include "DBUtil.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
DBConnection testDBConnection ;
//Sql在这儿
testDBConnection.executeSql("CREATE TABLE `tb_test2`(`id` INT NOT NULL,PRIMARY KEY(`id`));");
system("pause");
return 0 ;
}
查询Sql语句(querySql)的程序示例
#include "stdafx.h"
#include "winsock.h"
#include <mysql.h>
#include <iostream>
#include "DBConnection.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
DBConnection testDBConnection ;
MYSQL_ROW record;
//Sql在这儿
MYSQL_RES *results=testDBConnection.querySql("SELECT `id`,`age` FROM db_test.tb_test;");
while((record = mysql_fetch_row(results))) {
//这里的取值因Sql语句而异,还有record[2]等
printf("%s-%s\n", record[0], record[1]);
}
system("pause");
return 0 ;
}
C++连接数据库
最新推荐文章于 2024-08-30 05:00:00 发布