【问题标题】:asyncpg fetch feedback (python)asyncpg 获取反馈(python)
【发布时间】:2019-04-09 02:21:26
【问题描述】:

我一直在使用 psycopg2 来管理我的 PostgreSQL 数据库中的项目。最近有人建议我可以通过在我的代码中使用 asyncio 和 asyncpg 来改进我的数据库事务。我查看了 Stack Overflow 并阅读了文档中的示例。我已经能够创建表和插入记录,但是我无法获得我想要的执行反馈。

例如,在我的 psycopg2 代码中,我可以在插入记录之前验证表是否存在。

def table_exists(self, verify_table_existence, name):
    '''Verifies the existence of a table within the PostgreSQL database'''
    try:
        self.cursor.execute(verify_table_existence, name)

        answer = self.cursor.fetchone()[0]

        if answer == True:
            print('The table - {} - exists'.format(name))
            return True
        else:
            print ('The table - {} - does NOT exist'.format(name))
            return False

    except Exception as error:

        logger.info('An error has occurred while trying to verify the existence of the table {}'.format(name))
        logger.info('Error message: {}').format(error)
        sys.exit(1)

我无法使用 asyncpg 获得相同的反馈。我该如何做到这一点?

import asyncpg
import asyncio

async def main():
conn = await asyncpg.connect('postgresql://postgres:mypassword@localhost:5432/mydatabase')

answer = await conn.fetch('''
SELECT EXISTS (
SELECT 1
FROM   pg_tables
WHERE  schemaname = 'public'
AND    tablename = 'test01'
); ''')

await conn.close()

#####################
# the fetch returns
# [<Record exists=True>]
# but prints 'The table does NOT exist'
#####################

if answer == True:
    print('The table exists')   
else:
    print('The table does NOT exist')


asyncio.get_event_loop().run_until_complete(main())

【问题讨论】:

  • 您将 fetchone()[0] 与 psycopg2 一起使用,但仅将 fetch(...) 与 asyncpg 一起使用。前者将检索第一行的第一列,而后者将检索整个行列表。作为一个列表,它不等于True。尝试改用answer = await conn.fetchval(...)
  • 感谢工作。
  • 很高兴听到!我现在已将其转发为答案。

标签: python-3.x postgresql python-asyncio asyncpg


【解决方案1】:

您将 fetchone()[0] 与 psycopg2 一起使用,但仅将 fetch(...) 与 asyncpg 一起使用。前者将检索第一行的第一列,而后者将检索整个行列表。作为一个列表,它不等于True

要从单行中获取单个值,请使用 answer = await conn.fetchval(...) 之类的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-09
    • 2019-08-08
    相关资源
    最近更新 更多