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

I looked through the documentation, but did not find anything that allowed me to find out if the last command that I executed with cursor.execute ("...") was successfully executed.

I am expecting a response as "1 row affected."

+4
source share
2 answers

I expect some kind of exception should be increased .
If everything went fine, the error code is 00000 , and no exception will be raised.

In the case of create table 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
source

This is an old question, but one way to verify that psycopg2 works successfully is to simply look at the rowcount attribute for the cursor after your statement. This attribute returns the number of lines affected by the last execute .

eg.

 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 messagestatus , which returns a string that includes the type of the last operation performed along with the number of rows affected.

+3
source

Source: https://habr.com/ru/post/1395717/


All Articles