gpt4 book ai didi

c - 如何在 libdbi 中使用游标 - postgresql

转载 作者:行者123 更新时间:2023-11-30 15:55:43 25 4
gpt4 key购买 nike

我正在使用 libdbi 连接到一个大型 postgresql 数据库(3 亿条记录)并执行 SELECT * 查询,然后逐行显示结果。我正在获得完整的交换和内存,因此似乎启用了自动提交并将整个结果集加载到内存中。是否有任何选项可以禁用自动提交或至少在提交后保留游标,如java中的ResultSet.HOLD_CURSORS_OVER_COMMIT?我没有找到任何 dbi_conn_set_option 选项来执行此操作。这是我的代码:

dbi_conn conn;
dbi_result result;
int64_t id;

dbi_initialize(NULL);
conn = dbi_conn_new("pgsql");

if (conn == NULL)
{
printf("connection error.\n");
return EXIT_FAILURE;
}

dbi_conn_set_option(conn, "host", "127.0.0.1");
dbi_conn_set_option(conn, "username", "postgres");
dbi_conn_set_option(conn, "password", "123456");
dbi_conn_set_option(conn, "dbname", "backup");

if (dbi_conn_connect(conn) < 0)
{
printf("could not connect to database.\n");
return EXIT_FAILURE;
}

result = dbi_conn_query(conn, "SELECT * FROM tbl");
if (result)
{
while (dbi_result_next_row(result))
{
id = dbi_result_get_longlong(result, "_id");
printf("This is _id: %ld\n", id);
}

dbi_result_free(result);
}

dbi_conn_close(conn);
dbi_shutdown();

最佳答案

与自动提交无关。

解决内存不足问题的方法确实是使用游标一次获取 N 个结果,而不是一步获取所有结果。

libdbi 没有提供 SQL 游标的抽象,因此需要通过 SQL 查询来完成。

文档的 page on FETCH其示例中有完整的查询序列,展示了它是如何完成的。您需要通过两个循环在 C 中使用 libdbi 调用这些查询:一个外部循环从cursor_name 调用 FETCH N 直到没有任何内容可供提取,另一个内部循环处理该 FETCH 的结果,就像您的当前代码处理 select * 本身的结果。

关于c - 如何在 libdbi 中使用游标 - postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11844030/

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