poco-data模块

异常处理

try
{
*pwnd->m_spDb->m_spSession << "select f_id from t_user where f_name=? and f_pwd=?",
use(user), use(pwd), into(fid), now;
}
catch (const Poco::Exception& ex)
{
g_logger->error("cmdType_frontend_login: get user info failed. {}", ex.displayText());
}

事务处理

try
{
m_spDb->m_spSession->begin();
*m_spDb->m_spSession << strSql, now;
for (auto&it : vIdxCol)
{
*m_spDb->m_spSession << "CREATE INDEX idx_" << strInstId<< it << " ON " << tableName << " (" << it << ")", now;
*m_spDb->m_spSession << "CREATE INDEX idx_" << strInstId<< it<<"_alarm " << " ON " << tableName + "_alarm" << " (" << it << ")", now;
}
m_spDb->m_spSession->commit();
}
catch (const Poco::Exception& ex)
{
m_spDb->m_spSession->rollback();
g_logger->error("checkDbDataTable: create data table failed. {}", ex.displayText());
}

简单的选择

从数据库中取数据的操作与之类似。into关键字将数据库返回的值与C++对象匹配起来。并且支持指定默认值以防数据库返回null值。
此处需要注意的是,指定默认值的into,其定义为:into(T& t, const Position& pos, const T& def),使用的是模样类。在有些编译器下,不能隐式转换数据类型,所以需要显示的让第一个参数和第三个参数的数据类型保持一致。

Poco::Data::Session ses(MySQL::Connector::KEY, _dbConnString);
int count = 0;
ses << "SELECT COUNT(*) FROM SMART_U_STREET",into(count),now;
std::cout<<"street has "<<count<<std::endl;

std::string name;
session << "SELECT fN FROM tbA",into(name),now;
session << "SELECT fN FROM tbA",into(name,0,std::string("default")),now;

std::string name;
std::string match="wandoer";
session << "SELECT fN FROM tbA WHERE fN=?",into(name),use(match),now;

选择循环处理

struct MapObj
{
int64_t fk_user_id;
int64_t f_datasId;
int64_t f_datasType;
string f_datas;
};
MapObj mapObj;

Statement select(*m_spDbSrc->m_spSession);
select << "select fk_user_id,f_datasId,f_datasType,f_datas from t_ui_map",
into(mapObj.fk_user_id),into(mapObj.f_datasId),into(mapObj.f_datasType),into(mapObj.f_datas), range(0, 1);

try
{
m_spDbDest->m_spSession->begin();

while (!select.done())
{
select.execute();
*m_spDbDest->m_spSession << "insert into t_ui_map (fk_user_id,f_datasId,f_datasType,f_datas) values (?,?,?,?);",
useRef(mapObj.fk_user_id), useRef(mapObj.f_datasId), useRef(mapObj.f_datasType), useRef(mapObj.f_datas), now;
}
m_spDbDest->m_spSession->commit();
}
catch (const Poco::Exception& ex)
{
m_spDbDest->m_spSession->rollback();
g_logger->error("checkDbDataTable: create data table failed. {}", ex.displayText());
}

使用容器

Json::Value jsonObj;
typedef Poco::Tuple<int64_t, std::string> Person;
typedef std::vector<Person> People;
People people;

*pwnd->m_spDb->m_spSession << "select f_ui_id,f_param from t_user where f_param is not null",into(people), now;
for (auto&it: people)
{
jsonObj = readJsonFromString(it.get<1>());
jsonObj["userid"] = it.get<0>();
string ss = jsonObj.toStyledString();
jsonRet["datas"].append(jsonObj);
}

参数化

std::string name="wandoer"; 
session << "INSERT INTO tbA VALUES(?)",use(name), now;