mysql 操作类 c++_C++ 操作MySql类

// ConsoleApplication2.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"

#include

#include

#include

#include

#include "mysql.h"

#include

#include

using namespace std;

class MySQL

{

public:

MySQL();

inline BOOL InitSQL(const string&strHost, const string& strUserName, const string& strPwd, const string& strDataBase, const LONG lPort);

BOOL GetSqlInfo(const string& strSql);

BOOL DoSql(const string& strSql);

~MySQL();

private:

MYSQL myConnect;

MYSQL_RES *result;

};

MySQL::MySQL()

{

}

BOOL MySQL::InitSQL(const string&strHost, const string& strUserName, const string& strPwd, const string& strDataBase, const LONG lPort)

{

mysql_init(&myConnect);

if (mysql_real_connect(&myConnect, strHost.c_str(), strUserName.c_str(), strPwd.c_str(), strDataBase.c_str(), lPort, NULL, 0)){

mysql_query(&myConnect, "SET NAMES GBK");

return TRUE;

}

else{

return FALSE;

}

}

BOOL MySQL::GetSqlInfo(const string& strSql)

{

int res = mysql_query(&myConnect, strSql.c_str());

if(!res){

result = mysql_store_result(&myConnect);//保存查询到的数据到result

if(result == NULL){

return FALSE;

}

if(result->row_count > 0){

int j = mysql_num_fields(result);

MYSQL_ROW sql_row;

while (sql_row = mysql_fetch_row(result)){

for (int i = 0; i < j; i++){

printf("%s ", sql_row[i]);

}

printf("\n");

}

return TRUE;

}

else{

return FALSE;

}

}

else{

return FALSE;

}

}

BOOL MySQL::DoSql(const string& strSql)

{

if (!mysql_query(&myConnect, strSql.c_str())){

return TRUE;

}

else{

return FALSE;

}

}

MySQL::~MySQL()

{

if (result != NULL) mysql_free_result(result);//释放结果资源

mysql_close(&myConnect);//断开连接

}

int main()

{

MySQL sql;

if (sql.InitSQL("localhost", "root", "123456", "test", 3306)){

sql.GetSqlInfo("select * from test");

sql.DoSql("insert into test(ID ,username)values(2, '123')");

}

else{

cout << "sql inited failed"<

}

return 0;

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值