我想从我的表中获取名为'person'的行。我想在指标的帮助下做到这一点,以避免在此人没有名字时发生异常。怎么做?
我写了代码:
try
{
soci::statement st = (sql.prepare << "SELECT firstname FROM person;", soci::into(r, ind));
st.execute();
while (st.fetch())
{
if(sql.got_data())
{
switch(ind)
{
case soci::i_ok:
std::cout << r.get<std::string>(0) << "\n";
break;
case soci::i_null:
std::cout << "Person has no firstname!\n";
break;
}
}else
{
std::cout << "There's no such person!\n";
}
}
}
但是只有当我添加一行时才显示没有行:
std::cout << r.get<std::string>(0) << "\n";
在我的if语句之前,我才看到数据库中的firstnames。
答案 0 :(得分:1)
我认为您不需要soci::row
用于此目的,而是std::string
//...
std::string firstname;
soci::statement st = (sql.prepare << "SELECT firstname FROM person;"
, soci::into(firstname, ind));
//...
case soci::i_ok:
std::cout << firstname << std::endl;
break;
//...
答案 1 :(得分:0)
如果要查询整个数据库表行,则只能使用soci :: row。由于您只查询列,&#39; firstname&#39;你可以直接把它拿到一个字符串中。所以你的代码看起来像;
soci::indicator ind;
std::string sFirstName;
try
{
soci::statement st = (sql.prepare << "SELECT firstname FROM person;",
soci::into(sFirstName, ind));
st.execute();
while (st.fetch())
{
switch(ind)
{
case soci::i_ok: {
std::cout << sFirstName << std::endl;
break; }
case soci::i_null: {
std::cout << "Person has no first name!" << std::endl;
break;
}
}
}