pq async

本文探讨了如何使用libpq库以非阻塞方式执行SQL查询,并讨论了如何跟踪查询结果与原始请求的关联,以及是否可以使用回调机制代替PQgetResult函数。同时,文章提到了在事件循环中运行这些查询的可能性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

How to execute an async Query with libpq Ask Question Asked 6 months ago Active 6 months ago Viewed 63 times

1

I want to execute a SQL query with libpq in a non-blocking fashion. Thus I want to be notified when my query has finished executing.

As I understand this is supported by libpq if I use the asynchronous api.

With the PQsendQuery function I can send the query to the backend and with the PQgetResult function I can retrieve the result.

I call the PQsendQuery function multiple times without waiting for the previous one to finish.

Now I have the following questions:

How can I associate the results that I am going to pull later with PQgetResult to the corresponding query? Is there a method of using a callback instead of PQgetResult? Is there a way to run this in an event loop (e.g. libevent)? c postgresql libpq shareimprove this question asked Feb 6 at 16:57

Arwed Mett 1,32411 gold badge1313 silver badges2222 bronze badges add a comment 1 Answer active oldest votes

1

You misunderstand something here: PQsendQuery() sends an asynchronous query, meaning, that the command does not block until the results are available. However, you may not call PQsendQuery() again before all results were read!

From the manpage:

After successfully calling PQsendQuery, call PQgetResult one or more times to obtain the results. PQsendQuery may not be called again (on the same connection) until PQgetResult has returned a null pointer, indicating that the command is done.

As the manpage indicates, you would have to open several connections to run several concurrent queries. The different results are then associated with the different database handles.

The PostgreSQLc async io api does not provide callback mechanisms; however, this is not too hard to build yourself. libevent can be used, since you can retrieve the socket file descriptor with PQsocket(). However, quite some glue is needed to make it work.

转载于:https://my.oschina.net/innovation/blog/3085614

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值