1. 程式人生 > >mysql的c++封裝類

mysql的c++封裝類

//.h ////////////////////////////////////////////////////////////////////////////////
// CppMysql - A C++ wrapper around the mysql database library.
//
// Copyright (c) 2009 Rob Groves. All Rights Reserved. [email protected]
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement, is hereby granted, provided that the above copyright notice,
// this paragraph and the following two paragraphs appear in all copies,
// modifications, and distributions.
//
// IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
// INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
// PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
// EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
// ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". THE AUTHOR HAS NO OBLIGATION
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
// u can use it for anything, but u must show the source
// frome
http://blog.csdn.net/bat603

// by ben
// if u find some questions, please tell me with email
//
// V1.0  18/09/2009 -Initial Version for cppmysql
////////////////////////////////////////////////////////////////////////////////
#ifndef _CPP_MYSQL_1_H_
#define _CPP_MYSQL_1_H_ #include "mysql.h"
typedef unsigned int u_int;
typedef unsigned long u_long;
typedef MYSQL*  DB_HANDLE; class CppMySQL3DB; class CppMySQLQuery
{
 friend class CppMySQL3DB;
public:     CppMySQLQuery();  //當執行拷貝建構函式後,括號裡的類已經無效,不能再使用
    CppMySQLQuery(CppMySQLQuery& rQuery);  //當執行賦值建構函式後,=右邊的類已經無效,不能再使用
    CppMySQLQuery& operator=(CppMySQLQuery& rQuery);     virtual ~CppMySQLQuery();  u_long numRow();//多少行
    int numFields();//多少列     int fieldIndex(const char* szField);
 //0...n-1列
    const char* fieldName(int nCol);  //   const char* fieldDeclType(int nCol);
 //   int fieldDataType(int nCol);  u_long seekRow(u_long offerset);     int getIntField(int nField, int nNullValue=0);
    int getIntField(const char* szField, int nNullValue=0);     double getFloatField(int nField, double fNullValue=0.0);
    double getFloatField(const char* szField, double fNullValue=0.0);  //0...n-1列
    const char* getStringField(int nField, const char* szNullValue="");
    const char* getStringField(const char* szField, const char* szNullValue="");     const unsigned char* getBlobField(int nField, int& nLen);
    const unsigned char* getBlobField(const char* szField, int& nLen);     bool fieldIsNull(int nField);
    bool fieldIsNull(const char* szField);     bool eof();     void nextRow();     void finalize(); private:
 void freeRes();
    void checkVM();
private:
 MYSQL_RES*  _mysql_res;
 MYSQL_FIELD* _field;
 MYSQL_ROW  _row;
 u_long   _row_count;
 u_int   _field_count;
}; class CppMySQL3DB
{
public:     CppMySQL3DB();     virtual ~CppMySQL3DB();     int open(const char* host, const char* user, const char* passwd, const char* db,
  unsigned int port = 0, unsigned long client_flag = 0);     void close();  /* 返回控制代碼 */
 MYSQL* getMysql();  /* 處理返回多行的查詢,返回影響的行數 */
 //返回引用是因為在CppMySQLQuery的賦值建構函式中要把成員變數_mysql_res置為空
 CppMySQLQuery& querySQL(const char *sql);
 /* 執行非返回結果查詢 */
 int execSQL(const char* sql);
 /* 測試mysql伺服器是否存活 */
 int ping();
 /* 關閉mysql 伺服器 */
 int shutDown();
 /* 主要功能:重新啟動mysql 伺服器 */
 int reboot();
 /*
 * 說明:事務支援InnoDB or BDB表型別
    */
 /* 主要功能:開始事務 */
 int startTransaction();
 /* 主要功能:提交事務 */
 int commit();
 /* 主要功能:回滾事務 */
 int rollback();
 /* 得到客戶資訊 */
 const char * getClientInfo();
 /* 主要功能:得到客戶版本資訊 */
 const unsigned long  getClientVersion();
 /* 主要功能:得到主機資訊 */
 const char * getHostInfo();
 /* 主要功能:得到伺服器資訊 */
 const char * getServerInfo();
 /*主要功能:得到伺服器版本資訊*/
 const unsigned long  getServerVersion();
 /*主要功能:得到 當前連線的預設字符集*/
 const char *  getCharacterSetName();
 /* 得到系統時間 */
 const char * getSysTime();
 /* 建立新資料庫 */
 int createDB(const char* name);
 /* 刪除制定的資料庫*/
 int dropDB(const char* name);  bool tableExists(const char* table);     u_int lastRowId();     void setBusyTimeout(int nMillisecs){};
private:     CppMySQL3DB(const CppMySQL3DB& db);
    CppMySQL3DB& operator=(const CppMySQL3DB& db);     void checkDB(); private:
 /* msyql 連線控制代碼 */
 MYSQL* _db_ptr;
 CppMySQLQuery _db_query;
}; #endif //.cpp /////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// CppMysql - A C++ wrapper around the mysql database library.
//
// Copyright (c) 2009 Rob Groves. All Rights Reserved.
[email protected]

//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement, is hereby granted, provided that the above copyright notice,
// this paragraph and the following two paragraphs appear in all copies,
// modifications, and distributions.
//
// IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
// INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
// PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
// EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
// ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". THE AUTHOR HAS NO OBLIGATION
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
// u can use it for anything, but u must show the source
// frome
http://rainfish.cublog.cn

// by ben
//
// V1.0  18/09/2009 -Initial Version for cppmysql
//////////////////////////////////////////////////////////////////////////////// #include "cppmysql.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
CppMySQLQuery::CppMySQLQuery()
{
 _mysql_res = NULL;
 _field = NULL;
 _row = NULL;
 _row_count = 0;
 _field_count = 0; } CppMySQLQuery::CppMySQLQuery(CppMySQLQuery& rQuery)
{
 *this = rQuery;
} CppMySQLQuery& CppMySQLQuery::operator=(CppMySQLQuery& rQuery)
{
 if ( this == &rQuery )
  return *this;  _mysql_res = rQuery._mysql_res;
 _row = NULL;
 _row_count = 0;
 _field_count = 0;
 _field = NULL;  if ( _mysql_res != NULL )
 {
  //定位遊標位置到第一個位置
  mysql_data_seek(_mysql_res, 0);
  _row =  mysql_fetch_row( _mysql_res );
  _row_count = mysql_num_rows( _mysql_res );
   //得到欄位數量
  _field_count = mysql_num_fields( _mysql_res );
 }  rQuery._mysql_res = NULL;
 rQuery._field = NULL;
 rQuery._row = NULL;
 rQuery._row_count = 0;
 rQuery._field_count = 0;  return *this; } CppMySQLQuery::~CppMySQLQuery()
{
 freeRes();
} void CppMySQLQuery::freeRes()
{
 if ( _mysql_res != NULL )
 {
  mysql_free_result(_mysql_res);
  _mysql_res = NULL;
 }
} u_long CppMySQLQuery::numRow()
{
 return _row_count;
} int CppMySQLQuery::numFields()
{
 return _field_count;
} u_long CppMySQLQuery::seekRow(u_long offerset)
{
 if ( offerset < 0 )
  offerset = 0;
 if ( offerset >= _row_count )
  offerset = _row_count -1;  mysql_data_seek(_mysql_res, offerset);
 
 _row = mysql_fetch_row(_mysql_res);
 return offerset;
} int CppMySQLQuery::fieldIndex(const char* szField)
{
 if ( NULL == _mysql_res )
  return -1;
 if ( NULL == szField )
  return -1;  mysql_field_seek(_mysql_res, 0);//定位到第0列
 u_int i = 0;
 while ( i < _field_count )
 {
  _field = mysql_fetch_field( _mysql_res );
  if ( _field != NULL && strcmp(_field->name, szField) == 0 )//找到
   return i;   i++;
 }  return -1;
} const char* CppMySQLQuery::fieldName(int nCol)
{
 if ( _mysql_res == NULL )
  return NULL;  mysql_field_seek(_mysql_res, nCol);
 _field = mysql_fetch_field(_mysql_res);  if ( _field != NULL )
  return _field->name;
 else
  return  NULL;
} int CppMySQLQuery::getIntField(int nField, int nNullValue/*=0*/)
{
 if ( NULL == _mysql_res )
  return nNullValue;
 
 if ( nField + 1 > (int)_field_count )
  return nNullValue;
 
 if ( NULL == _row )
  return nNullValue;
 
 return atoi(_row[nField]);
} int CppMySQLQuery::getIntField(const char* szField, int nNullValue/*=0*/)
{
 if ( NULL == _mysql_res || NULL == szField )
  return nNullValue;
 
 if ( NULL == _row )
  return nNullValue;  const char* filed = getStringField(szField);  if ( NULL == filed )
  return nNullValue;  return atoi(filed);
} const char* CppMySQLQuery::getStringField(int nField, const char* szNullValue/*=""*/)
{
 if ( NULL == _mysql_res )
  return szNullValue;  if ( nField + 1 > (int)_field_count )
  return szNullValue;  if ( NULL == _row )
  return szNullValue;  return _row[nField];
}
   
const char* CppMySQLQuery::getStringField(const char* szField, const char* szNullValue/*=""*/)
{
 if ( NULL == _mysql_res )
  return szNullValue;  int nField = fieldIndex(szField);
 if ( nField == -1 )
  return szNullValue;
 
 return getStringField(nField);
} double CppMySQLQuery::getFloatField(int nField, double fNullValue/*=0.0*/)
{
 const char* field = getStringField(nField);  if ( NULL == field )
  return fNullValue;  return atol(field);
}
 
double CppMySQLQuery::getFloatField(const char* szField, double fNullValue/*=0.0*/)
{
 const char* field = getStringField(szField);
 if ( NULL == field )
  return fNullValue;  return atol(field);
} void CppMySQLQuery::nextRow()
{
 if ( NULL == _mysql_res )
  return;  _row = mysql_fetch_row(_mysql_res);
} bool CppMySQLQuery::eof()
{
 if ( _row == NULL )
  return true;  return false;
} CppMySQL3DB::CppMySQL3DB()
{
 _db_ptr = NULL;
} CppMySQL3DB::~CppMySQL3DB()
{
 if ( _db_ptr != NULL )
 {
  close();
 }
} int CppMySQL3DB::open(const char* host, const char* user, const char* passwd, const char* db,
  unsigned int port /*= 0*/, unsigned long client_flag /*= 0*/)
{
 int ret = -1;  _db_ptr = mysql_init(NULL);
 if( NULL == _db_ptr )
  goto EXT;
 
 //如果連線失敗,返回NULL。對於成功的連線,返回值與第1個引數的值相同。
 if ( NULL == mysql_real_connect( _db_ptr, host, user, passwd, db,port, NULL, client_flag) )
  goto EXT;  //選擇制定的資料庫失敗
 //0表示成功,非0值表示出現錯誤。
 if ( mysql_select_db( _db_ptr, db ) != 0 )
 {
  mysql_close(_db_ptr);
  _db_ptr = NULL;
  goto EXT;
 }  ret = 0;
EXT:
 //初始化mysql結構失敗
 if ( ret == -1 && _db_ptr != NULL )
 {
  mysql_close( _db_ptr );
  _db_ptr = NULL;
 }  return ret;
} void CppMySQL3DB::close()
{
 if ( _db_ptr != NULL )
 {
  mysql_close( _db_ptr );
  _db_ptr = NULL;
 }
} MYSQL* CppMySQL3DB::getMysql()
{
 return _db_ptr;
} /* 處理返回多行的查詢,返回影響的行數 */
CppMySQLQuery& CppMySQL3DB::querySQL(const char *sql)
{
 if ( !mysql_real_query( _db_ptr, sql, strlen(sql) ) )
 {
  _db_query._mysql_res = mysql_store_result( _db_ptr );
//   _db_query._row =  mysql_fetch_row( _db_query._mysql_res );
//   _db_query._row_count = mysql_num_rows( _db_query._mysql_res );
//   //得到欄位數量
//   _db_query._field_count = mysql_num_fields( _db_query._mysql_res );
 }  return _db_query;
} /* 執行非返回結果查詢 */
int CppMySQL3DB::execSQL(const char* sql)
{
 if( !mysql_real_query( _db_ptr, sql, strlen(sql) ) )
 {
  //得到受影響的行數
  return (int)mysql_affected_rows(_db_ptr) ;
 }
 else
 {
  //執行查詢失敗
  return -1;
 }
} /* 測試mysql伺服器是否存活 */
int CppMySQL3DB::ping()
{
 if( mysql_ping(_db_ptr) == 0 )
  return 0;
 else
  return -1;
} /* 關閉mysql 伺服器 */
int CppMySQL3DB::shutDown()
{
 if( mysql_shutdown(_db_ptr,SHUTDOWN_DEFAULT) == 0 )
  return 0;
 else
  return -1;
} /* 主要功能:重新啟動mysql 伺服器 */
int CppMySQL3DB::reboot()
{
 if(!mysql_reload(_db_ptr))
  return 0;
 else
  return -1;
} /*
* 說明:事務支援InnoDB or BDB表型別
*/
/* 主要功能:開始事務 */
int CppMySQL3DB::startTransaction()
{
 if(!mysql_real_query(_db_ptr, "START TRANSACTION" ,
  (unsigned long)strlen("START TRANSACTION") ))
 {
  return 0;
 }
 else
  //執行查詢失敗
  return -1;
} /* 主要功能:提交事務 */
int CppMySQL3DB::commit()
{
 if(!mysql_real_query( _db_ptr, "COMMIT",
  (unsigned long)strlen("COMMIT") ) )
 {
  return 0;
 }
 else     
  //執行查詢失敗
  return -1;
} /* 主要功能:回滾事務 */
int CppMySQL3DB::rollback()
{
 if(!mysql_real_query(_db_ptr, "ROLLBACK",
  (unsigned long)strlen("ROLLBACK") ) )
  return 0;
 else 
  //執行查詢失敗
  return -1;
} /* 得到客戶資訊 */
const char * CppMySQL3DB::getClientInfo()
{
 return mysql_get_client_info();
} /* 主要功能:得到客戶版本資訊 */
const unsigned long  CppMySQL3DB::getClientVersion()
{
 return mysql_get_client_version();
} /* 主要功能:得到主機資訊 */
const char * CppMySQL3DB::getHostInfo()
{
 return mysql_get_host_info(_db_ptr);
} /* 主要功能:得到伺服器資訊 */
const char * CppMySQL3DB::getServerInfo()
{
 return mysql_get_server_info( _db_ptr ); }
/*主要功能:得到伺服器版本資訊*/
const unsigned long  CppMySQL3DB::getServerVersion()
{
 return mysql_get_server_version(_db_ptr); } /*主要功能:得到 當前連線的預設字符集*/
const char *  CppMySQL3DB::getCharacterSetName()
{
 return mysql_character_set_name(_db_ptr); } /* 得到系統時間 */
const char * CppMySQL3DB::getSysTime()
{
 //return ExecQueryGetSingValue("select now()");
 return NULL; } /* 建立新資料庫 */
int CppMySQL3DB::createDB(const char* name)
{
 char temp[1024];  sprintf(temp, "CREATE DATABASE %s", name);  if(!mysql_real_query( _db_ptr, temp, strlen(temp)) )
  return 0;
 
 else
  //執行查詢失敗
  return -1;
} /* 刪除制定的資料庫*/
int CppMySQL3DB::dropDB(const char*  name)
{
 char temp[1024];
 
 sprintf(temp, "DROP DATABASE %s", name);  if(!mysql_real_query( _db_ptr, temp, strlen(temp)) )
  return 0;
 else
  //執行查詢失敗
  return -1;
} bool CppMySQL3DB::tableExists(const char* table)
{
 return false;
} u_int CppMySQL3DB::lastRowId()
{
 return 0;
}