Psycopg3 无法异步连接

发布于 2025-01-09 00:09:25 字数 657 浏览 2 评论 0原文

无法使用异步 psycopg3 连接 postgres 数据库:

import asyncio
import psycopg

async def main():
    async with await psycopg.AsyncConnection.connect('postgresql://xxxxxxxxxxx') as con:
        async with con.cursor() as cur:
            print(await cur.execute('select 1 a').fetchall())

if __name__ == '__main__':
    asyncio.run(main())

我收到错误:

psycopg.InterfaceError: Psycopg cannot use the 'ProactorEventLoop' to run in async mode. Please use a compatible event loop, for instance by setting 'asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())'

在 Windows 10、Python 3.9、Psycopg 3.0.8 上

Unable to connect postgres database using async psycopg3 :

import asyncio
import psycopg

async def main():
    async with await psycopg.AsyncConnection.connect('postgresql://xxxxxxxxxxx') as con:
        async with con.cursor() as cur:
            print(await cur.execute('select 1 a').fetchall())

if __name__ == '__main__':
    asyncio.run(main())

I get error:

psycopg.InterfaceError: Psycopg cannot use the 'ProactorEventLoop' to run in async mode. Please use a compatible event loop, for instance by setting 'asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())'

On Windows 10, Python 3.9, Psycopg 3.0.8

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南笙 2025-01-16 00:09:25

这是工作解决方案

import asyncio
import sys

import psycopg


async def main():

    async with await psycopg.AsyncConnection.connect('postgresql://xxxxxxxxxxx') as con:
        async with con.cursor() as cur:
            print(await (await cur.execute('select 1 a')).fetchall())

if __name__ == '__main__':

    if sys.platform == "win32":
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    asyncio.run(main())

Here is the working solution

import asyncio
import sys

import psycopg


async def main():

    async with await psycopg.AsyncConnection.connect('postgresql://xxxxxxxxxxx') as con:
        async with con.cursor() as cur:
            print(await (await cur.execute('select 1 a')).fetchall())

if __name__ == '__main__':

    if sys.platform == "win32":
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    asyncio.run(main())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文