介绍:
这里推荐一种做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;
}