gpt4 book ai didi

c++ - 使用 SOCI 从 PostgreSQL 数据库获取数据时出现错误

转载 作者:行者123 更新时间:2023-11-29 12:34:02 24 4
gpt4 key购买 nike

我在 PostgreSQL 中有一个数据库。我有 sql 查询(顺便说一句,它在 PostgreSQL 中运行良好,所以 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;

创建日期在 PostgreSQL 中定义为 creation_date Date;。例如,查询返回(取决于我的数据库中有什么):

size | creation_date
21 | 12-31-2012
18 | 04-03-2002

我正在使用 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;
}

但是当我尝试运行应用程序时出现了这个错误(编译没问题):

terminate called after throwing an instance of 'std::bad_cast'
what(): std::bad_cast Interrupt (core dumped)

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

也许问题在于 creation_date 是 DATE 而 tm 也保持时间......?如果是,如何解决?

最佳答案

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

您的问题是,COUNT(*) 返回 bigint(或 int8)类型的值,如所述here ,soci 将 bigint 转换为 long long int类型,如所述in this chart .如果类型不完全匹配,将抛出 bad_cast 异常。

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

关于c++ - 使用 SOCI 从 PostgreSQL 数据库获取数据时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11614105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com