我一直在使用psycopg2来管理PostgreSQL数据库中的项目。最近有人建议我可以在代码中使用异步和异步by来改进我的数据库事务。我已经查看过Stack溢出,并阅读了文档中的示例。我已经能够创建表和插入记录,但我还没有得到我想要的执行反馈。
例如,在我的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)我还没有能够得到相同的反馈使用异步板。我怎样才能做到这一点?
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())发布于 2018-11-06 18:47:41
您在psycopg2中使用了fetchone()[0],而在异步but中只使用了fetch(...)。前者将检索第一行的第一列,而后者将检索整个行列表。作为一个列表,它不等于True。
若要从单个行中获取单个值,请使用类似于answer = await conn.fetchval(...)的内容。
https://stackoverflow.com/questions/53159231
复制相似问题