psycopg2.InternalError:我如何获得更多有用的信息?

AP2*_*257 8 python postgresql

我在Python脚本中运行此命令:

try: 
    print sql_string
    cursor.execute(sql_string)
except:
    print sys.exc_info()
Run Code Online (Sandbox Code Playgroud)

得到:

(<class 'psycopg2.InternalError'>, InternalError('current transaction is aborted, commands ignored until end of transaction block\n',), <traceback object at 0x1010054d0>)
Run Code Online (Sandbox Code Playgroud)

但是,如果我sql_string从psql命令行尝试,它可以正常工作.我知道脚本连接到数据库没关系,因为我可以运行其他命令.

如何让Python为我提供有关此命令在脚本中失败的原因的更多有用信息?

Mat*_*ood 8

试试这个:

try:
    print sql_string
    cursor.execute(sql_string)
except Exception, e:
    print e.pgerror
Run Code Online (Sandbox Code Playgroud)

如果你仍然得到"当前事务被中止,命令被忽略,直到事务块结束",那么你的错误会进一步回到你的事务中,而这个查询只会因为先前的查询失败而失败(从而使整个事务无效).

有关pgerror的详细信息,请参阅http://initd.org/psycopg/docs/module.html#exceptions上的文档.


nat*_*ill 7

您还可以拖尾postgresql的输出以查看导致错误的查询:

$ tail -f /var/log/postgresql/postgresql.log
Run Code Online (Sandbox Code Playgroud)

这通常比编辑脚本以调试它更容易.

  • 查看日志,我立即看到另一个表插入失败,这创建了事务块。我认为问题所在的表格插入很好。 (2认同)