Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

psycopg

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."

like image 526
kev Avatar asked Feb 10 '12 03:02

kev


People also ask

How do you check if a table exists in Postgres using Python?

SELECT 1 FROM information_schema. tables WHERE table_schema = 'schema_name' AND table_name = 'table_name'; SELECT EXISTS ( SELECT FROM pg_tables WHERE schemaname = 'schema_name' AND tablename = 'table_name' );


1 Answers

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.

like image 131
Akshat Mahajan Avatar answered Sep 28 '22 06:09

Akshat Mahajan