Question

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.

Was it helpful?

Solution

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;
//...

OTHER TIPS

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;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top