2

我一直在使用 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())
4

1 回答 1

2

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

要从单行获取单个值,请使用类似answer = await conn.fetchval(...).

于 2018-11-06T18:47:41.137 回答