- 爱易网页
-
Linux
- 本人对MYSQL C API做的一个封装,希望对linux C++程序员有点帮助,同时欢迎拍砖!该怎么解决
日期:2014-05-16 浏览次数:20657 次
本人对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 <string.h>
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: %s\n ", mysql_error(&mysql));
return false;
}
printf( "Logged on to database sucessfully\n ");
_bOpen = true;
return _bOpen;