psycopg2.InternalError:如何获取更有用的信息?

10 投票
2 回答
13413 浏览
提问于 2025-04-16 04:10

我在一个Python脚本里运行这个命令:

try: 
    print sql_string
    cursor.execute(sql_string)
except:
    print sys.exc_info()

结果是:

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

不过,如果我在psql命令行里试这个sql_string,它就能正常工作。我知道脚本能顺利连接到数据库,因为我可以运行其他命令。

我该怎么做才能让Python给我更多有用的信息,告诉我为什么这个命令在脚本里失败了呢?

2 个回答

8

你还可以查看postgresql的输出,看看是什么查询导致了错误:

$ tail -f /var/log/postgresql/postgresql.log

这样做通常比修改脚本来调试要简单。

10

试试这个:

try:
    print sql_string
    cursor.execute(sql_string)
except Exception, e:
    print e.pgerror

如果你仍然看到“当前事务已中止,命令在事务块结束之前被忽略”的错误,那说明你的错误在事务的更早之前,当前这个查询失败是因为之前的某个查询出错了(这样就导致整个事务无效了)。

关于pgerror的详细信息可以在文档中找到,链接是 http://initd.org/psycopg/docs/module.html#exceptions

撰写回答