linux c mysql 封装_本人对MYSQL C API做的一个封装,希望对linux C++程序员有点帮助,同时欢迎拍砖!...
本人對MYSQL??C?API做的一個封裝,使用很簡單,構造一個對象,就可直接執行SQL,但對于需返回結果的查詢語句,對其數據集沒做封裝,仍需直接調用mysql?c?api對其進行處理,本人將下次完成,不管如何,歡迎大家多提寶貴的意見!
//CDataBase.h
#ifndef?CDATABASE_H
#define?CDATABASE_H
#include?"stdio.h"
#include?"/usr/include/mysql/mysql.h"
#include
class?CDataBase
{
public:
CDataBase(const?char?*host,?const?char?*user,?const?char?*passwd,?const?char?*db);
~CDataBase();
bool?ExecuteSql(const?char*?chSql);
MYSQL_RES?*?OpenRecordset(const?char*?chSql);
void?FreeResult(MYSQL_RES?*result);
private:
MYSQL?mysql;
bool?_bOpen;
const?char?*_host;
const?char?*_user;
const?char?*_passwd;
const?char?*_db;
protected:
bool?Open();
void?Close();
bool?GetConState();
};
#endif
------------------------------------------
//CDataBase.cpp
#include?"cdatabase.h"
CDataBase::CDataBase(const?char?*host,?const?char?*user,?const?char?*passwd,?const?char?*db)
{
_host?=?host;
_user?=?user;
_passwd?=?passwd;
_db?=?db;
_bOpen?=?false;
Open();
}
CDataBase::~CDataBase()
{
Close();
}
bool?CDataBase::GetConState()
{
return?_bOpen;
}
bool?CDataBase::Open()
{
if(?!mysql_init(&mysql)?)
{
printf("nFailed?to?initate?MySQL?connection");
return?false;
}
if?(!mysql_real_connect(&mysql,_host,_user,_passwd,_db,0,NULL,0))
{
printf(?"Failed?to?connect?to?MySQL:?Error:?%sn",?mysql_error(&mysql));
return?false;
}
printf("Logged?on?to?database?sucessfullyn");
_bOpen?=?true;
return?_bOpen;
}
void?CDataBase::Close()
{
if(_bOpen)
{
mysql_close(&mysql);
_bOpen?=?false;
}
}
bool?CDataBase::ExecuteSql(const?char*?chSql)
{
if(!GetConState())
return?false;
if(mysql_real_query(&mysql,chSql,strlen(chSql))==0)
return?true;
}
MYSQL_RES?*?CDataBase::OpenRecordset(const?char*?chSql)
{
MYSQL_RES?*rs?=?NULL;
if(ExecuteSql(?chSql?))
{
rs?=?mysql_store_result(&mysql);
}
return?rs;
}
void?CDataBase::FreeResult(MYSQL_RES?*result)
{
if(result)
mysql_free_result(result);
}
-------------------------------------------------
//Test.cpp
#ifdef?HAVE_CONFIG_H
#include
#endif
#include
#include
#include?"cdatabase.h"
using?namespace?std;
int?main(int?argc,?char?*argv[])
{
const?char?*host?=?"127.0.0.1";
const?char?*user?=?"root";
const?char?*pwd?=?NULL;
const?char?*dbn?=?"test";
//構造對象
CDataBase?*db?=?new?CDataBase(host,user,pwd,dbn);
//創建一個張
db->ExecuteSql(?"create?table?tt1(id?int?,name?varchar(20))");
//插入一個數據
db->ExecuteSql(?"insert?into?tt1(id,name)values('31','abc')");
//查詢數據
MYSQL_RES?*res?=?NULL;
MYSQL_ROW?row;
res?=?db->OpenRecordset("select?*?from?tt");
if(res)
{
cout
總結
以上是生活随笔為你收集整理的linux c mysql 封装_本人对MYSQL C API做的一个封装,希望对linux C++程序员有点帮助,同时欢迎拍砖!...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql数据库导入外部数据乱码么_解决
- 下一篇: 网校mysql设计规范_网校数据库设计