How do I know if I have successfully created a table (Python, Psycopg2)?

ぐ巨炮叔叔 提交于 2019-12-04 21:21:35

问题


I've looked at the documentations but haven't found anything that lets me know if the last command i've execute via cursor.execute("...") is successful.

I'm expecting a reply like "1 row affected."


回答1:


I'd expect some kind of exception to be risen.
If everything went ok – the error code is 00000 and no exception will get risen.

In create table case, you can always double check:

try:
    cur.execute("SELECT ouch FROM aargh;")
except Exception, e:
    pass

errorcodes.lookup(e.pgcode[:2])
# 'CLASS_SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION'
errorcodes.lookup(e.pgcode)
# 'UNDEFINED_TABLE'



回答2:


This is an old question, but one way to check for a successful operation with psycopg2 is simply to look at the rowcount attribute for the cursor after your statement. This attribute returns the number of rows affected by the last execute statement.

e.g.

connection = psycopg2.connect(dbname="foo",user="postgres")
cur = connection.cursor()
cur.execute("INSERT INTO foo VALUES (%s, %s)", (1,2))
cur.rowcount # returns 1
cur.execute("SELECT * FROM foo")
cur.rowcount # returns 0

A similar attribute is statusmessage, which returns a string including the type of the last operation performed along with the number of rows affected.



来源:https://stackoverflow.com/questions/9222256/how-do-i-know-if-i-have-successfully-created-a-table-python-psycopg2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!