简体   繁体   中英

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.

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

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM