Reputation: 4311
I want to get rows from my table called 'person'. I would like to do it with help of indicators in order to avoid an exception when the person has no firstname. How to do this?
I wrote the code:
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";
}
}
}
But it shows no rows, only when I add a line:
std::cout << r.get<std::string>(0) << "\n";
BEFORE my if statement, only then I see firstnames from database.
Upvotes: 0
Views: 1352
Reputation: 1202
You can only use the soci::row if you are querying for the whole database table row. Since you only query the column, 'firstname' you can directly fetch it into a string. so your code would look like;
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;
}
}
}
Upvotes: 0
Reputation: 2944
I think you need to use not soci::row
for this purpose but 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;
//...
Upvotes: 1