Search code examples
c++soci

Get rows from table using SOCI with soci::indicators [C++]


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.


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