使用SOCI从PostgreSQL数据库获取数据时出错

Bri*_*own 1 c++ postgresql soci postgresql-9.1

我在PostgreSQL中有一个数据库.我有SQL查询(在PostgreSQL中btw工作得很好,所以sql代码没有错):

SELECT COUNT(*) as size, creation_date FROM item INNER JOIN raf_item USING (id) INNER JOIN item_detail USING (id) GROUP BY creation_date;
Run Code Online (Sandbox Code Playgroud)

其中创建日期定义为creation_date Date;PostgreSQL.例如,查询返回(取决于我在数据库中的内容):

size | creation_date
21   | 12-31-2012
18   | 04-03-2002
Run Code Online (Sandbox Code Playgroud)

我正在使用SOCI + C++从此查询中获取数据.我的整个C++代码:

#include <iostream>
#include <cstdlib>
#include <soci.h>
#include <string>
#include <postgresql/soci-postgresql.h>
using namespace std;

bool connectToDatabase(soci::session &sql, string databaseName, string user, string password)
{
    try
    {
        sql.open(soci::postgresql, "dbname=" +databaseName + " user="+user + " password="+password);
    }
    catch (soci::postgresql_soci_error const & e)
    {
        cerr << "PostgreSQL error: " << e.sqlstate() << " " << e.what() << std::endl;
        return false;
    }
    catch (std::exception const & e)
    {
        cerr << "Some other error: " << e.what() << std::endl;
        return false;
    }
    return true;
}

void getDataFromDatabase(soci::session &sql)
{
    soci::row r;
    sql << "select count(*) as size, creation_date from item inner join raf_item using (id) inner join item_detail using (id) group by creation_date;", soci::into(r);
    for(std::size_t i = 0; i != r.size(); ++i)
    {
        cout << r.get<int>(i);
        tm when = r.get<tm>(i);
        cout << asctime(&when);
    }
}

int main(int argc, char **argv)
{
    soci::session sql;
    bool success = connectToDatabase(sql, "testdb", "testuser", "pass");
    if (success)
    {
        cout << "Connected.\n";
        getDataFromDatabase(sql);
    }

    else
        cout << "Not connected.\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试运行应用程序时,我得到了这个错误(编译很好):

在抛出'std :: bad_cast'的实例后调用终止
what():std :: bad_cast中断(core dumped)

请帮忙,当编译正常时我真的不知道如何解决这个问题.

也许问题是creation_date是DATE而且tm还保留时间......?如果是这样,如何解决这个问题?

nik*_*iko 5

虽然您确实解决了问题,但您发布的代码更多的是解决方法,而不是问题的真正解决方案.

您的问题是,COUNT(*)返回BIGINT(或INT8)的值输入,如所描述这里,和SOCI转换BIGINT到一个long long int类型,如所描述的在该图表中.如果类型不匹配,则会抛出bad_cast异常.

因此,您的问题中的代码应该是cout << r.get<long long>(i);避免bad_cast异常.