首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取反馈(python)

问获取反馈(python)
EN

Stack Overflow用户
提问于 2018-11-05 17:23:26
回答 1查看 3.3K关注 0票数 2

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

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

代码语言:javascript
复制
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)

我还没有能够得到相同的反馈使用异步板。我怎样才能做到这一点?

代码语言:javascript
复制
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())
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-06 18:47:41

您在psycopg2中使用了fetchone()[0],而在异步but中只使用了fetch(...)。前者将检索第一行的第一列,而后者将检索整个行列表。作为一个列表,它不等于True。

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53159231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档