2014年01月28日 星期二 15:45
tntdb提供了一组统一的数据库访问API,可以支持MySQL,SQLite3等多种常用的数据库。其API丰富而易用,也支持Connection Pool和Statment Cache等高级特性。
经过最近的实践,我感觉,习惯了这些C++编写的API之后,就再也不想去使用C语言的API了。我认为前者的易用程度和开发效率已经一点都不输于PHP等动态编程语言。
编程示例如下:
#include <iostream>
#include <tntdb/connection.h>
#include <tntdb/statement.h>
#include <tntdb/connect.h>
#include <tntdb/result.h>
#include <tntdb/row.h>
using namespace std;
using namespace tntdb;
int main(int argc,char **argv) {
try {
string connstr="mysql:";
connstr += "host=10.1.1.161;";
connstr += "db=test;";
connstr += "user=mengguang;";
connstr += "passwd=1234qwer;";
Connection conn = connect(connstr);
Statement stmt = conn.prepare(
"insert into friends(name,email) values(:name,:email)");
stmt.set("name","mengguang");
stmt.set("email","mengguang@gmail.com");
stmt.execute();
cout << "ID: " << conn.lastInsertId() << endl;
stmt.set("name","mengkang").set("email",
"mengkang@163.com").execute();
cout << "ID: " << conn.lastInsertId() << endl;
Result result = conn.select("select * from friends");
Result::const_iterator it=result.begin();
for(;it!=result.end();it++) {
Row row=*it;
int id; string name; string email;
row.reader().get(id).get(name).get(email);
cout << id << "|" << name << "|" << email << endl;
}
Statement pstmt = conn.prepare(
"select email from friends where name=:name");
pstmt.set("name","mengguang");
Statement::const_iterator sit=pstmt.begin();
for(;sit!=pstmt.end();sit++) {
Row row=*sit;
string email;
row[0].get(email);
cout << "got email: " << email << endl;
}
Value v = conn.selectValue(
"select email from friends where name='mengguang'");
cout << "got email: " << v.getString() << endl;
int n = conn.execute("delete from friends");
cout << "rows deleted: " << n << endl;
} catch (exception &e) {
cout << "ERROR: " << e.what() << endl;
}
return 0;
}
参考资料:
Zeuux © 2025
京ICP备05028076号