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

后端 未结 2 521
没有蜡笔的小新
没有蜡笔的小新 2021-02-14 20:14

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 expect

2条回答
  •  再見小時候
    2021-02-14 21:12

    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.

提交回复
热议问题