案例代碼下載
開發包下載
介紹:
這裡推薦一種做MYSQL用戶端開發的精簡開發包。所有功能被定義為兩個包含檔案。使用者可以用提供的API和標頭檔中的boost::shared_ptr管理MYSQL串連和結果設定。
使用代碼:
MYSQL的精簡開發包
類結構圖表如下:
該結構非常簡單。唯一的不同是成員函數CMysqlConn::Query。該函數有一個摸版參數'ProcessQuery',這是一個'policy'類用於客戶需求的API。不同使用者有不同的資料庫使用意圖。一些使用者想要得到資料來做出結論。一些使用者想要插入或更新資料,這就不需要返回任何資料。其他使用者可能只是得到資料的ID的類型,使用的是'where'指令。
基於Andrei Alexandrescu的"Modern C++ design"一書中的定址方案,'Query'成員函數使用模板來區別於通常的查詢演算法。
我為CMysqlConn::Query定義了三個類。以下是使用案例:
查詢資料庫需要返回資料:
CMysqlSet rset=conn.Query<WithData>("select * from mytable");
查詢資料庫不需要返回資料:
bool ret =conn.Query<NoData>("insert into mytable values
(5000, 'testing message')");
查詢資料庫只是獲得值:
pair<bool, string> value=conn.Query<CheckOneRecord>
("select field from mytable where errorcode='2005'");
使用者可以定義他們自己的類,如下:
struct Nodata
{
//Define your return type
typedef boolReturnType;
//Define your failed return function for the query failure case
static ReturnType ReturnInFail() {return false;}
//Define your records processing implementation after the
//query statement is successfully issued.
static ReturnType DeepQuery(ConnPtr ptr) {return true;}
};
這是使用開發包的代碼案例:
Collapseint Test()
{
string query="select * from mytable";
CMysqlConn conn("myhost","mytable", "login","password");
if (conn)
{
CMysqlSet rset=conn.Query<WithData>(query);
if (rset)
{
cout<<"I got a result";
unsigned size=rset.NumberOfRecords();
for (unsigned int i=0;i<size; i++){
CMysqlRow row=rset.GetNextRow();
if (row)
{
for (unsigned int j=0; j<row.NumberOfFields();j++)
{
cout<<row[j];
}
cout<<endl;
}
}
}
cout<<"Last error is
"<<conn.GetLastfiled1()<<":"<<conn.GetLastErrorString()<<endl;
string updateQuery="insert into mytable values (5000, 'testing message')";
conn.Query<NoData>(updateQuery);
//
// Query single data test
//
cout<<"query single data..."<<endl;
pair<bool, string> value=conn.Query<CheckOneRecord>
("select filed1s from mytable where filed1='2005'");
if (value.first)
{
cout<<"get value of "<<value.second<<endl;
}
}
return 0;
}