POCO Data User Guide
按Poco的文档,本文缩写、改编、注释POCO Data User Guide的内容,介绍Poco的数据库操作。原文见http://pocoproject.org/docs/00200-DataUserManual.html。
先介绍一个简单例子,无须解释,其意自明。
#include"Poco/Data/Common.h"#include"Poco/Data/SQLite/Connector.h"#includeusingnamespacePoco::Data;voidinit()
{
SQLite::Connector::registerConnector();
}voidshutdown()
{
SQLite::Connector::unregisterConnector();
}intmain(intargc,char*argv[])
{
init();
Session ses("SQLite","sample.db");intcount=0;
ses<
std::cout<
shutdown();
}
Session
表示与数据库的连接,每个Session有两个要素,一是Poco表示数据库种类的类型标识,二是连接每种数据库所需的一个字符串。注意,实际的软件中这两个参数一般不会硬编码在代码中。
以SQLite为例
Session ses("SQLite","sample.db");
或
Session ses(SessionFactory::instance()::create("SQLite","sample.db"));
读取和写入数据:占位符placeholder,use(),into()
写入操作中使用placeholder和use()
std::stringaName("Peter");
ses<
读取操作中使用placeholder和into()
std::stringaName;
ses<
也可以同时使用use()和into()
std::stringaName;
std::stringmatch("Peter")
ses<
poco_assert (aName==match);
一般情况下,数据表有多列,用如下形式
std::stringfirstName("Peter";
std::stringlastName("Junior");intage=0;
ses<
注意,placeholder与use或into的顺序是一一对应的。
Statement用于表示SQL语句
原型
templateStatement Session::operator<
两种赋值方式,第一种方式会立即执行语句
std::stringaName("Peter");
Statement stmt=( ses<
第二种赋值方式可以把语句保存起来,稍后再执行
std::stringaName("Peter");
Statement stmt=( ses<
stmt.execute();
poco_a