首页 > 解决方案 > 在 asyncpg 中出现“准备好的语句错误”

问题描述

我正在尝试通过使用连接池来处理来自 PostgreSQL 服务器的一些数据。有一个警告提到了这个问题,这显然是由于使用了 'pgbouncer' 工具见下文

但是我正在使用该createpool()函数来获取连接对象:

self.pg_con=await asyncpg.create_pool(dsn=dsn,database=db,user=user,password=_db_pass)





Traceback (most recent call last):
  File "C:\Users\User\Desktop\Py-Workspace\env\lib\site-packages\discord\client.py", line 270, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\User\Desktop\Py-Workspace\cogs\levels_3.py", line 40, in on_message
    user=await self.bot.pg_con.fetch("SELECT * FROM users WHERE user_id = $1 AND guild_id= $2",author_id,guild_id)
  File "C:\Users\User\Desktop\Py-Workspace\env\lib\site-packages\asyncpg\pool.py", line 542, in fetch
    return await con.fetch(query, *args, timeout=timeout)
  File "C:\Users\User\Desktop\Py-Workspace\env\lib\site-packages\asyncpg\connection.py", line 420, in fetch
    return await self._execute(query, args, 0, timeout)
  File "C:\Users\User\Desktop\Py-Workspace\env\lib\site-packages\asyncpg\connection.py", line 1402, in _execute
    result, _ = await self.__execute(
  File "C:\Users\User\Desktop\Py-Workspace\env\lib\site-packages\asyncpg\connection.py", line 1411, in __execute
    return await self._do_execute(query, executor, timeout)
  File "C:\Users\User\Desktop\Py-Workspace\env\lib\site-packages\asyncpg\connection.py", line 1423, in _do_execute
    stmt = await self._get_statement(query, None)
  File "C:\Users\User\Desktop\Py-Workspace\env\lib\site-packages\asyncpg\connection.py", line 328, in _get_statement
    statement = await self._protocol.prepare(stmt_name, query, timeout)
  File "asyncpg\protocol\protocol.pyx", line 163, in prepare
asyncpg.exceptions.DuplicatePreparedStatementError: prepared statement "__asyncpg_stmt_1__" already exists
HINT:
NOTE: pgbouncer with pool_mode set to "transaction" or
"statement" does not support prepared statements properly.
You have two options:

* if you are using pgbouncer for connection pooling to a
  single server, switch to the connection pool functionality
  provided by asyncpg, it is a much better option for this
  purpose;

* if you have no option of avoiding the use of pgbouncer,
  then you can set statement_cache_size to 0 when creating
  the asyncpg connection object.

标签: pythonpostgresqlasynchronousprepared-statementasyncpg

解决方案


推荐阅读