vc連mysql類

在vc中通過連接池操作mysql(api方式),附c++訪問mysql的封裝類
2008年06月11日 星期三 15:31

在有大量節點訪問的數據庫設計中,經常要使用到連接池來管理所有的連接.
一般方法是:建立兩個連接句柄隊列,空閒的等待使用的隊列和正在使用的隊列.
當要查詢時先從空閒隊列中獲取一個句柄,插入到正在使用的隊列,再用這個句柄做數據庫操作,完畢後一定要從使用隊列中刪除,再插入到空閒隊列.
代碼如下:
MySQLMan.h
// MySQLMan.h: interface for the CMySQLMan class.
//
//////////////////////////////////////////////////////////////////////
#include <mysql.h>
#pragma comment(lib,"libmySQL.lib")

#include <list>

typedef std::list<MYSQL *> CONNECTION_HANDLE_LIST;
typedef std::list<MYSQL *>::iterator ITER_CONNECTION_HANDLE_LIST;

#define CONNECTION_NUM 10 //同時打開的連接數

class CMySQLMan
{
public:
CMySQLMan();
CMySQLMan(const char *host, const char *user, const char *password, const char *db, unsigned int port=3306);
virtual ~CMySQLMan();

public:
bool ConnectDB(); //連接數據庫
MYSQL_RES* SelectRecord(const char *szSql); //選擇記錄,返回結果集
bool SelectDB(const char *szDB); //選擇數據庫
bool UpdateRecord(const char *szSql); //更新記錄
bool InsertRecord(const char *szSql); //插入記錄
bool DelRecord(const char *szSql); //刪除記錄

BOOL IsEnd(MYSQL_RES *myquery); //是否最後
void SeekData(MYSQL_RES *myquery, int offset); //查找指定數據
void FreeRecord(MYSQL_RES *myquery); //釋放結果集
unsigned int GetFieldNum(MYSQL_RES *myquery); //得到字段數
MYSQL_ROW GetRecord(MYSQL_RES *myquery); //得到結果(一個記錄)
my_ulonglong GetRowNum(MYSQL_RES *myquery); //得到記錄數
char* OutErrors(MYSQL* pMySql); //輸出錯誤信息

char* GetState(); //服務器狀態
char* GetServerInfo(); //服務器信息
int GetProtocolInfo(); //協議信息
char* GetHostInfo(); //主機信息
char* GetClientInfo(); //客戶機信息
char* GetFieldName(MYSQL_RES *myquery, int FieldNum); //字段名

bool LockTable(const char *TableName, const char *Priority); //對特定表加鎖
bool UnlockTable(); //解鎖
bool SetCharset();
//int CreateDB(char *db); //創建數據庫,返回錯誤信息
//int DropDB(char *db); //刪除數據庫,返回錯誤信息

MYSQL* GetIdleMySql(); //提取一個空閒句柄供使用
void SetIdleMysql(MYSQL* pMySql); //從使用隊列中釋放一個使用完畢的句柄,插入到空閒隊列

public:
//MYSQL m_mysql; //數據庫連接句柄
MYSQL_ROW m_row; //記錄集(單行)
MYSQL_FIELD *m_field; //字段信息(結構體)

//創建兩個隊列
CONNECTION_HANDLE_LIST m_lsBusyList; //正在使用的連接句柄
CONNECTION_HANDLE_LIST m_lsIdleList; //未使用的連接句柄

CRITICAL_SECTION m_csList;

public:
char m_host[20]; //主機
char m_user[20]; //用戶名
char m_password[20]; //密碼
char m_db[20]; //數據庫名
unsigned int m_port; //端口
};

MySQLMan.cpp
// MySQLMan.cpp: implementation of the MySQLMan class.
//
//////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "MySQLMan.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CMySQLMan::CMySQLMan()
{

}

CMySQLMan::CMySQLMan(const char *host, const char *user, const char *password, const char *db, unsigned int port/* =3306 */)
{
strcpy(m_host, host);
strcpy(m_user, user);
strcpy(m_password, password);
strcpy(m_db, db);
m_port = port;

InitializeCriticalSection(&m_csList);
}

CMySQLMan::~CMySQLMan()
{
for (ITER_CONNECTION_HANDLE_LIST iter=m_lsBusyList.begin(); iter != m_lsBusyList.end(); iter++)
{
mysql_close((*iter));
}

for (ITER_CONNECTION_HANDLE_LIST iter=m_lsIdleList.begin(); iter != m_lsIdleList.end(); iter++)
{
mysql_close((*iter));
}

DeleteCriticalSection(&m_csList);
}

bool CMySQLMan::ConnectDB()
{
//同時打開CONNECTION_NUM個連接
try
{
for (int i=0; i<CONNECTION_NUM; ++i)
{
MYSQL *pMySql = mysql_init((MYSQL*)NULL);
if (pMySql != NULL)
{
if (!mysql_real_connect(pMySql,m_host,m_user,m_password,m_db,m_port,NULL,0))
{
OutErrors(pMySql);
return false;
}
m_lsIdleList.push_back(pMySql);
}
}
}
catch (...)
{
return false;
}
return true;
}

MYSQL* CMySQLMan::GetIdleMySql()
{
MYSQL* pMySql = NULL;
EnterCriticalSection(&m_csList);
if (m_lsIdleList.size() > 0)
{
pMySql = m_lsIdleList.front();
m_lsIdleList.pop_front();
m_lsBusyList.push_back(pMySql);
}
else
{
pMySql = NULL;
}
LeaveCriticalSection(&m_csList);

return pMySql;
}

void CMySQLMan::SetIdleMysql(MYSQL* pMySql)
{
EnterCriticalSection(&m_csList);
m_lsBusyList.remove(pMySql);
m_lsIdleList.push_back(pMySql);
LeaveCriticalSection(&m_csList);
}

MYSQL_RES* CMySQLMan::SelectRecord(const char *szSql)
{
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return NULL;
}
if(mysql_query(pMySql,szSql))
return NULL;
MYSQL_RES *myquery = NULL;
myquery = mysql_store_result(pMySql);
SetIdleMysql(pMySql);

return myquery;
}

bool CMySQLMan::InsertRecord(const char *szSql)
{
bool bRet = false;
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return false;
}
if(mysql_query(pMySql,szSql))
{
bRet = true;
}
SetIdleMysql(pMySql);

return bRet;
}

bool CMySQLMan::UpdateRecord(const char *szSql)
{
bool bRet = false;
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return false;
}
if(mysql_query(pMySql,szSql))
{
bRet = true;
}
SetIdleMysql(pMySql);

return bRet;
}

bool CMySQLMan::DelRecord(const char *szSql)
{
bool bRet = false;
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return false;
}
if(mysql_query(pMySql,szSql))
{
bRet = true;
}
SetIdleMysql(pMySql);

return bRet;
}

bool CMySQLMan::SelectDB(const char *szDB)
{
bool bRet = false;
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return false;
}
if (mysql_select_db(pMySql,szDB))
bRet = false;
else
bRet = true;
SetIdleMysql(pMySql);

return bRet;
}

my_ulonglong CMySQLMan::GetRowNum(MYSQL_RES *myquery)
{
return mysql_num_rows(myquery);
}

MYSQL_ROW CMySQLMan::GetRecord(MYSQL_RES *myquery)
{
m_row = mysql_fetch_row(myquery);

return m_row;
}

unsigned int CMySQLMan::GetFieldNum(MYSQL_RES *myquery)
{
return mysql_num_fields(myquery);
}

void CMySQLMan::FreeRecord(MYSQL_RES *myquery)
{
mysql_free_result(myquery);
}

//int CMySQLMan::CreateDB(char *db)
//{
// return mysql_create_db(&m_mysql,db);
//}

void CMySQLMan::SeekData(MYSQL_RES *myquery, int offset)
{
mysql_data_seek(myquery,offset);
}


char * CMySQLMan::OutErrors(MYSQL *pMySql)
{
return const_cast<char *>(mysql_error(pMySql));
}

BOOL CMySQLMan::IsEnd(MYSQL_RES *myquery)
{
return mysql_eof(myquery);
}

char* CMySQLMan::GetFieldName(MYSQL_RES *myquery, int FieldNum)
{
m_field = mysql_fetch_field_direct(myquery, FieldNum);

return m_field->name;
}

char * CMySQLMan::GetClientInfo()
{
return const_cast<char *>(mysql_get_client_info());
}

char* CMySQLMan::GetHostInfo()
{
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return NULL;
}
return const_cast<char *>(mysql_get_host_info(pMySql));
}

int CMySQLMan::GetProtocolInfo()
{
int iRet = 0;
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return NULL;
}
iRet = mysql_get_proto_info(pMySql);
SetIdleMysql(pMySql);

return iRet;
}

char* CMySQLMan::GetServerInfo()
{
static char szRet[1024];
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return NULL;
}
_tcscpy(szRet, const_cast<char *>(mysql_get_server_info(pMySql)));
SetIdleMysql(pMySql);

return szRet;
}

char* CMySQLMan::GetState()
{
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return NULL;
}
static char szRet[1024];
_tcscpy(szRet,const_cast<char *>(mysql_stat(pMySql)));
SetIdleMysql(pMySql);

return szRet;
}

bool CMySQLMan::SetCharset()
{
bool bRet = false;
char szSql[50];
strcpy(szSql, "set names gb2312");
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return false;
}
if (mysql_query(pMySql, szSql))
bRet = true;
SetIdleMysql(pMySql);

return bRet;
}

//LOCK TABLES tbl1 READ, tbl2 WRITE
bool CMySQLMan::LockTable(const char *TableName, const char *Priority)
{
bool bRet = false;
char szSql[50];
sprintf(szSql, "LOCK TABLES %s %s", TableName, Priority);
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return false;
}
if (mysql_query(pMySql, szSql))
bRet = true;
SetIdleMysql(pMySql);

return bRet;
}

bool CMySQLMan::UnlockTable()
{
bool bRet = false;
MYSQL *pMySql = GetIdleMySql();
if (pMySql == NULL)
{
return false;
}
if(mysql_query(pMySql,"UNLOCK TABLES"))
bRet = true;
SetIdleMysql(pMySql);

return bRet;

}

 

以下原文:http://lhsplayer.blog.163.com/blog/static/4708828520084112405957/

 

/*
* project:
* 通用模塊 ( 用 c++ 處理 mysql 數據庫類,像ADO )
*
* description:
*
* 通過DataBase,RecordSet,Record,Field類,實現對mysql數據庫的操作
* 包括連接、修改、添加、刪除、查詢等等,像ADO一樣操作數據庫,使
* 用方便
*
* ( the end of this file have one sample,
* welcom to use... )
*
*
* file:zlb_mysql.h
*
* author: @ zlb
*
* time:2005-12-12
*
*
*
--*/

#ifndef ZLB_MYSQL_H
#define ZLB_MYSQL_H


#include "mysql.h"

#include <iostream>
#include <vector>
#include <string>

using namespace std;

namespace zlb_mysql{

/*
* 字段操作
*/
class Field
{
public :
/* 字段名稱 */
vector<string> m_name;
/* 字段類型 */
vector<enum_field_types> m_type;
public :
Field();
~Field();


/* 是否是數字 */
bool IsNum(int num);
/* 是否是數字 */
bool IsNum(string num);
/* 是否是日期 */
bool IsDate(int num);
/* 是否是日期 */
bool IsDate(string num);
/* 是否是字符 */
bool IsChar(int num);
/* 是否是字符 */
bool IsChar(string num);
/* 是否爲二進制數據 */
bool IsBlob(int num);
/* 是否爲二進制數據 */
bool IsBlob(string num);
/* 得到指定字段的序號 */
int GetField_NO(string field_name);
};




/*
* 1 單條記錄
* 2 [int ]操作 [""]操作
*/
class Record
{
public:
/* 結果集 */
vector<string> m_rs;
/* 字段信息 佔用4字節的內存 當記錄數很大是回產生性能問題 */
Field *m_field;
public :
Record(){};
Record(Field* m_f);
~Record();


void SetData(string value);
/* [""]操作 */
string operator[](string s);
string operator[](int num);
/* null值判斷 */
bool IsNull(int num);
bool IsNull(string s);
/* 用 value tab value 的形式 返回結果 */
string GetTabText();
};




/*
* 1 記錄集合
* 2 [int ]操作 [""]操作
* 3 表結構操作
* 4 數據的插入修改
*/
class RecordSet
{
private :
/* 記錄集 */
vector<Record> m_s;
/* 遊標位置*/
unsigned long pos;
/* 記錄數 */
int m_recordcount;
/* 字段數 */
int m_field_num;
/* 字段信息 */
Field m_field;

MYSQL_RES * res ;
MYSQL_FIELD * fd ;
MYSQL_ROW row;
MYSQL* m_Data ;
public :
RecordSet();
RecordSet(MYSQL *hSQL);
~RecordSet();

/* 處理返回多行的查詢,返回影響的行數 */
int ExecuteSQL(const char *SQL);
/* 得到記錄數目 */
int GetRecordCount();
/* 得到字段數目 */
int GetFieldNum();
/* 向下移動遊標 */
long MoveNext();
/* 移動遊標 */
long Move(long length);
/* 移動遊標到開始位置 */
bool MoveFirst();
/* 移動遊標到結束位置 */
bool MoveLast();
/* 獲取當前遊標位置 */
unsigned long GetCurrentPos()const;
/* 獲取當前遊標的對應字段數據 */
bool GetCurrentFieldValue(const char * sFieldName,char *sValue);
bool GetCurrentFieldValue(const int iFieldNum,char *sValue);
/* 獲取遊標的對應字段數據 */
bool GetFieldValue(long index,const char * sFieldName,char *sValue);
bool GetFieldValue(long index,int iFieldNum,char *sValue);
/* 是否到達遊標尾部 */
bool IsEof();

 

/* 返回字段 */
Field* GetField();
/* 返回字段名 */
const char * GetFieldName(int iNum);
/* 返回字段類型 */
const int GetFieldType(char * sName);
const int GetFieldType(int iNum);
/* 返回指定序號的記錄 */
Record operator[](int num);

};

/*
* 1 負責數據庫的連接關閉
* 2 執行sql 語句(不返回結果)
* 3 處理事務
*/
class DataBase
{
public :
DataBase();
~DataBase();
private :
/* msyql 連接句柄 */
MYSQL* m_Data;
public :
/* 返回句柄 */
MYSQL * GetMysql();
/* 連接數據庫 */
int Connect(string host, string user,
string passwd, string db,
unsigned int port,
unsigned long client_flag);

/* 關閉數據庫連接 */
void DisConnect();
/* 執行非返回結果查詢 */
int ExecQuery(string sql);
/* 測試mysql服務器是否存活 */
int Ping();
/* 關閉mysql 服務器 */
int ShutDown();
/* 主要功能:重新啓動mysql 服務器 */
int ReBoot();
/*
* 說明:事務支持InnoDB or BDB表類型
*/
/* 主要功能:開始事務 */
int Start_Transaction();
/* 主要功能:提交事務 */
int Commit();
/* 主要功能:回滾事務 */
int Rollback();
/* 得到客戶信息 */
const char * Get_client_info();
/* 主要功能:得到客戶版本信息 */
const unsigned long Get_client_version();
/* 主要功能:得到主機信息 */
const char * Get_host_info();
/* 主要功能:得到服務器信息 */
const char * Get_server_info();
/*主要功能:得到服務器版本信息*/
const unsigned long Get_server_version();
/*主要功能:得到 當前連接的默認字符集*/
const char * Get_character_set_name();

/* 主要功能返回單值查詢 */
char * ExecQueryGetSingValue(string sql);

/* 得到系統時間 */
const char * GetSysTime();
/* 建立新數據庫 */
int Create_db(string name);
/* 刪除制定的數據庫*/
int Drop_db(string name);
};


};

#endif //ZLB_MYSQL_H

/*
* project:
* 通用模塊 ( 用 c++ 處理 mysql 數據庫類,像ADO )
*
* description:
*
* 通過DataBase,RecordSet,Record,Field類,實現對mysql數據庫的操作
* 包括連接、修改、添加、刪除、查詢等等,像ADO一樣操作數據庫,使
* 用方便
*
* ( the end of this file have one sample,
* welcom to use... )
*
*
* file:zlb_mysql.cpp
*
* author: @ zlb
*
* time:2005-12-12
*
*
*
--*/

#include "stdafx.h"
#include "zlb_mysql.h"

namespace zlb_mysql{

/* +++++++++++++++++++++++++++++++++++++++++++++++++++ */
/*
* 字段操作
*/
Field::Field(){}
Field::~Field(){}
/*
* 是否是數字
*/
bool Field::IsNum(int num)
{
if(IS_NUM(m_type[num]))
return true;
else
return false;
}
/*
* 是否是數字
*/
bool Field::IsNum(string num)
{
if(IS_NUM(m_type[GetField_NO(num)]))
return true;
else
return false;
}
/*
* 是否是日期
*/
bool Field::IsDate(int num)
{
if( FIELD_TYPE_DATE == m_type[num] ||
FIELD_TYPE_DATETIME == m_type[num] )
return true;
else
return false;
}
/* 是否是日期 */
bool Field::IsDate(string num)
{
int temp;
temp=GetField_NO(num);
if(FIELD_TYPE_DATE == m_type[temp] ||
FIELD_TYPE_DATETIME == m_type[temp] )
return true;
else
return false;
}
/*
* 是否是字符
*/
bool Field::IsChar(int num)
{
if(m_type[num]==FIELD_TYPE_STRING ||
m_type[num]==FIELD_TYPE_VAR_STRING ||
m_type[num]==FIELD_TYPE_CHAR )
return true;
else
return false;

}
/*
* 是否是字符
*/
bool Field::IsChar(string num)
{
int temp;
temp=this->GetField_NO (num);
if(m_type[temp]==FIELD_TYPE_STRING ||
m_type[temp]==FIELD_TYPE_VAR_STRING ||
m_type[temp]==FIELD_TYPE_CHAR )
return true;
else
return false;
}
/*
* 是否爲二進制數據
*/
bool Field::IsBlob(int num)
{
if(IS_BLOB(m_type[num]))
return true;
else
return false;
}
/*
* 是否爲二進制數據
*/
bool Field::IsBlob(string num)
{
if(IS_BLOB(m_type[GetField_NO(num)]))
return true;
else
return false;
}
/*
* 得到指定字段的序號
*/
int Field::GetField_NO(string field_name)
{

for(unsigned int i=0;i<m_name.size ();i++)
{
if(!m_name[i].compare (field_name))
return i;

}
return -1;
}
/*-----------------------------------------------------*/

/* +++++++++++++++++++++++++++++++++++++++++++++++++++ */
/*
* 1 單條記錄
* 2 [int ]操作 [""]操作
*/

Record::Record(Field * m_f)
{
m_field =m_f;
}
Record::~Record(){};

void Record::SetData(string value)
{
m_rs.push_back (value);
}
/* [""]操作 */
string Record::operator[](string s)
{
return m_rs[m_field->GetField_NO(s)];
}
string Record::operator[](int num)
{
return m_rs[num];
}
/* null值判斷 */
bool Record::IsNull(int num)
{
if("" == m_rs[num].c_str ())
return true;
else
return false;
}
bool Record::IsNull(string s)
{
if("" == m_rs[m_field->GetField_NO(s)].c_str())
return true;
else return false;
}
/* 主要-功能:用 value tab value 的形式 返回結果 */
string Record::GetTabText()
{
string temp;
for(unsigned int i=0 ;i<m_rs.size();i++)
{
temp+=m_rs[i];
if(i<m_rs.size ()-1)
temp+="/t";
}
return temp;
}
/*-----------------------------------------------------*/


/* +++++++++++++++++++++++++++++++++++++++++++++++++++ */
/*
* 1 記錄集合
* 2 [int ]操作 [""]操作
* 3 表結構操作
* 4 數據的插入修改
*/
RecordSet::RecordSet()
{
res = NULL;
row = NULL;
pos = 0;
}
RecordSet::RecordSet(MYSQL *hSQL)
{
res = NULL;
row = NULL;
m_Data = hSQL;
pos = 0;
}
RecordSet::~RecordSet()
{
}
/*
* 處理返回多行的查詢,返回影響的行數
* 成功返回行數,失敗返回-1
*/
int RecordSet::ExecuteSQL(const char *SQL)
{
if ( !mysql_real_query(m_Data,SQL,strlen(SQL)))
{
//保存查詢結果
res = mysql_store_result(m_Data );
//得到記錄數量
m_recordcount = (int)mysql_num_rows(res) ;
//得到字段數量
m_field_num = mysql_num_fields(res) ;
for (int x = 0 ; fd = mysql_fetch_field(res); x++)
{
m_field.m_name.push_back(fd->name);
m_field.m_type.push_back(fd->type);
}
//保存所有數據
while (row = mysql_fetch_row(res))
{
Record temp(&m_field);
for (int k = 0 ; k < m_field_num ; k++ )
{

if(row[k]==NULL||(!strlen(row[k])))
{
temp.SetData ("");
}
else
{

temp.SetData(row[k]);
}

}
//添加新記錄
m_s.push_back (temp);
}
mysql_free_result(res ) ;

return m_s.size();
}
return -1;
}
/*
* 向下移動遊標
* 返回移動後的遊標位置
*/
long RecordSet::MoveNext()
{
return (++pos);
}
/* 移動遊標 */
long RecordSet::Move(long length)
{
int l = pos + length;

if(l<0)
{
pos = 0;
return 0;
}else
{
if(l >= m_s.size())
{
pos = m_s.size()-1;
return pos;
}else
{
pos = l;
return pos;
}
}

}
/* 移動遊標到開始位置 */
bool RecordSet::MoveFirst()
{
pos = 0;
return true;
}
/* 移動遊標到結束位置 */
bool RecordSet::MoveLast()
{
pos = m_s.size()-1;
return true;
}
/* 獲取當前遊標位置 */
unsigned long RecordSet::GetCurrentPos()const
{
return pos;
}
/* 獲取當前遊標的對應字段數據 */
bool RecordSet::GetCurrentFieldValue(const char * sFieldName,
char *sValue)
{
strcpy(sValue,m_s[pos][sFieldName].c_str());
return true;
}
bool RecordSet::GetCurrentFieldValue(const int iFieldNum,char *sValue)
{
strcpy(sValue,m_s[pos][iFieldNum].c_str());
return true;
}
/* 獲取遊標的對應字段數據 */
bool RecordSet::GetFieldValue(long index,const char * sFieldName,
char *sValue)
{
strcpy(sValue,m_s[index][sFieldName].c_str());
return true;
}
bool RecordSet::GetFieldValue(long index,int iFieldNum,char *sValue)
{
strcpy(sValue,m_s[index][iFieldNum].c_str());
return true;
}
/* 是否到達遊標尾部 */
bool RecordSet::IsEof()
{
return (pos == m_s.size())?true:false;
}
/*
* 得到記錄數目
*/
int RecordSet::GetRecordCount()
{
return m_recordcount;
}
/*
* 得到字段數目
*/
int RecordSet::GetFieldNum()
{
return m_field_num;
}
/*
* 返回字段
*/
Field * RecordSet::GetField()
{
return &m_field;
}
/* 返回字段名 */
const char * RecordSet::GetFieldName(int iNum)
{
return m_field.m_name.at(iNum).c_str();
}
/* 返回字段類型 */
const int RecordSet::GetFieldType(char * sName)
{
int i = m_field.GetField_NO(sName);
return m_field.m_type.at(i);
}
const int RecordSet::GetFieldType(int iNum)
{
return m_field.m_type.at(iNum);
}
/*
* 返回指定序號的記錄
*/
Record RecordSet::operator[](int num)
{
return m_s[num];
}

/* -------------------------------------------------- */

/* +++++++++++++++++++++++++++++++++++++++++++++++++++ */
/*
* 1 負責數據庫的連接關閉
* 2 執行sql 語句(不返回結果)
* 3 處理事務
*/
DataBase::DataBase()
{
m_Data = NULL;
}
DataBase::~DataBase()
{
if(NULL != m_Data)
{
DisConnect();
}
}
/* 返回句柄 */
MYSQL * DataBase::GetMysql()
{
return m_Data;
}
/*
* 主要功能:連接數據庫
* 參數說明:
* 1 host 主機ip地址或者時主機名稱
* 2 user 用戶名
* 3 passwd 密碼
* 4 db 欲連接的數據庫名稱
* 5 port 端口號
* 6 uinx 嵌套字
* 7 client_flag 客戶連接參數
* 返回值: 0成功 -1 失敗
*/
int DataBase::Connect(string host, string user,
string passwd, string db,
unsigned int port,
unsigned long client_flag)
{
if((m_Data = mysql_init(NULL)) &&
mysql_real_connect( m_Data, host.c_str(),
user.c_str(), passwd.c_str(),
db.c_str(),port , NULL,
client_flag))
{
//選擇制定的數據庫失敗
if ( mysql_select_db( m_Data, db.c_str () ) < 0 )
{
mysql_close( m_Data) ;
return -1 ;
}
}
else
{
//初始化mysql結構失敗
mysql_close( m_Data );
return -1 ;
}
//成功
return 0;
}
/*
* 關閉數據庫連接
*/
void DataBase::DisConnect( )
{
mysql_close(m_Data) ;
}
/*
* 主要功能: 執行非返回結果查詢
* 參數:sql 待執行的查詢語句
* 返回值; n爲成功 表示受到影響的行數 -1 爲執行失敗
*/
int DataBase::ExecQuery(string sql)
{
if(!mysql_real_query(m_Data,sql.c_str (),(unsigned long)sql.length()) )
{
//得到受影響的行數
return (int)mysql_affected_rows(m_Data) ;
}
else
{
//執行查詢失敗
return -1;
}
}
/*
* 主要功能:測試mysql服務器是否存活
* 返回值:0 表示成功 -1 失敗
*/
int DataBase::Ping()
{
if(!mysql_ping(m_Data))
return 0;
else
return -1;
}
/*
* 主要功能:關閉mysql 服務器
* 返回值;0成功 -1 失敗
*/
int DataBase::ShutDown()
{
if(!mysql_shutdown(m_Data,SHUTDOWN_DEFAULT))
return 0;
else
return -1;
}
/*
* 主要功能:重新啓動mysql 服務器
* 返回值;0表示成功 -1 表示失敗
*/
int DataBase::ReBoot()
{
if(!mysql_reload(m_Data))
return 0;
else
return -1;
}

/*
* 說明:事務支持InnoDB or BDB表類型
*/
/*
* 主要功能:開始事務
*/
int DataBase::Start_Transaction()
{
if(!mysql_real_query(m_Data, "START TRANSACTION" ,
(unsigned long)strlen("START TRANSACTION") ))
{
return 0;
}
else
//執行查詢失敗
return -1;
}
/*
* 主要功能:提交事務
* 返回值:0 表示成功 -1 表示失敗
*/
int DataBase::Commit()
{

if(!mysql_real_query( m_Data, "COMMIT",
(unsigned long)strlen("COMMIT") ) )
{
return 0;
}
else
//執行查詢失敗
return -1;
}
/*
* 主要功能:回滾事務
* 返回值:0 表示成功 -1 表示失敗
*/
int DataBase::Rollback()
{

if(!mysql_real_query(m_Data, "ROLLBACK",
(unsigned long)strlen("ROLLBACK") ) )
return 0;
else
//執行查詢失敗
return -1;
}
/* 得到客戶信息 */
const char * DataBase::Get_client_info()
{
return mysql_get_client_info();
}
/*主要功能:得到客戶版本信息*/
const unsigned long DataBase::Get_client_version()
{
return mysql_get_client_version();
}
/* 主要功能:得到主機信息 */
const char * DataBase::Get_host_info()
{
return mysql_get_host_info(m_Data);
}
/* 主要功能:得到服務器信息 */
const char * DataBase::Get_server_info()
{
return mysql_get_server_info( m_Data );
}
/* 主要功能:得到服務器版本信息 */
const unsigned long DataBase::Get_server_version()
{
return mysql_get_server_version(m_Data);
}
/*主要功能:得到 當前連接的默認字符集*/
const char * DataBase::Get_character_set_name()
{
return mysql_character_set_name(m_Data);
}
/*
* 主要功能返回單值查詢
*/
char * DataBase::ExecQueryGetSingValue(string sql)
{
MYSQL_RES * res;
MYSQL_ROW row ;
char *p = NULL;
if(!mysql_real_query( m_Data, sql.c_str(),(unsigned long)sql.length()))
{
//保存查詢結果
res = mysql_store_result( m_Data ) ;
row = mysql_fetch_row( res ) ;
p = ((row[0]==NULL)||(!strlen(row[0])))?"-1":row[0];
mysql_free_result( res ) ;
}
else
//執行查詢失敗
p = "-1";
return p;
}
/*
* 得到系統時間
*/
const char * DataBase::GetSysTime()
{
return ExecQueryGetSingValue("select now()");
}
/*
* 主要功能:建立新數據庫
* 參數:name 爲新數據庫的名稱
* 返回:0成功 -1 失敗
*/
int DataBase::Create_db(string name)
{
string temp ;
temp="CREATE DATABASE ";
temp+=name;
if(!mysql_real_query( m_Data,temp.c_str () ,
(unsigned long)temp.length ()) )
return 0;

else
//執行查詢失敗
return -1;
}
/*
* 主要功能:刪除制定的數據庫
* 參數:name 爲欲刪除數據庫的名稱
* 返回:0成功 -1 失敗
*/
int DataBase::Drop_db(string name)
{
string temp ;
temp="DROP DATABASE ";
temp+=name;
if(!mysql_real_query( m_Data,temp.c_str () ,
(unsigned long)temp.length ()) )
return 0;
else
//執行查詢失敗
return -1;
}
/*-----------------------------------------------------*/
};

/*
* 使用例子
*/
#include "zlb_mysql.h"
using namespace std;
void main()
{
zlb_mysql::DataBase zlb;
//連接數據庫
if(-1 == zlb.Connect("localhost"/*本地數據庫,可以是遠程 ip*/,
"root"/*用戶名*/,"apple"/*密碼*/,
"test"/*數據庫名*/,
0,0/*兩個標誌,mysql文檔有說明,一般爲0*/))
{
std::cout<<"connect failed "<<std::endl;
}
else
{
std::cout<<"connect success"<<std::endl;
}
//通過返回的數據庫句柄,建立記錄急,你可以通過返回的這個句柄建立多個記錄急
zlb_mysql::RecordSet rs(zlb.GetMysql());
rs.ExecuteSQL("select * from testtable");//這個語句大家都知道是什麼意思了

cout<<rs.GetRecordCount()/*返回的總的記錄數*/<<endl;
cout<<rs.GetFieldNum()/*返回的總的字段數*/<<endl;
cout<<rs[0].GetTabText()/*返回第一條記錄,你也可以rs[1].GetTabText()
如果你有多條記錄,
*/
<<endl;
/*實現遍列,也可以使用後面的遍列方式*/
for(int i=0;i<rs.GetRecordCount();++i)
{
for(int j =0;j<rs.GetFieldNum();++j)
cout<<rs[i][j];
cout<<endl;
}

zlb_mysql::Field *fd = rs.GetField();/*你可以通過這樣的方式,獲取字段的信息*/
cout<<fd->GetField_NO("Password")/*返回我表裏的 Password 字段的位置,不
是記錄的位置*/
<<endl;
cout<<rs[0]["Password"]<<endl;/*輸出第0行第Password列的值*/
cout<<rs[0][fd->GetField_NO("Password")]<<endl;/*你也可以這樣*/

cout<<rs.GetFieldName(0)/*獲取字段的名字*/<<endl;
cout<<rs.GetFieldType("UserName")/*獲取字段的類型,是mysql裏定義的*/<<endl;

cout<<rs.GetCurrentPos()/*獲取當前記錄的位置*/<<endl;
char s[50];
rs.GetCurrentFieldValue(1,s);/*獲取當前記錄對應字段的值*/
cout<<s<<endl;

cout<<rs.Move(1)<<endl;/*移動遊標,正數往前 負數往後*/
cout<<rs.GetCurrentPos()<<endl;
rs.GetCurrentFieldValue(1,s);
cout<<s<<endl;


rs.MoveFirst();/*移動遊標到最前*/
while(!rs.IsEof()/*判斷是否到達遊標尾,實現遍列*/)
{
rs.GetCurrentFieldValue("UserName",s);
cout<<s<<"/t";
rs.GetCurrentFieldValue("Password",s);
cout<<s<<"/t/n";
rs.MoveNext();
}

rs.GetFieldValue(0,"UserName",s);/*獲取指定行 的記錄值*/
cout<<s<<"/t";
rs.GetFieldValue(0,"Password",s);
cout<<s<<"/t/n";
}

發佈了12 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章