Python – Connect, Query a Postgresql database

The following code, will connect to a Postgresql database and execute a query. It will also throw and error in case the connection cannot be made.

 

#!/usr/bin/python
import psycopg2
con = None
try:
        con = psycopg2.connect(dbname = 'dvdrental', user = 'postgres')
        cursor = con.cursor()
        cursor.execute('SELECT * from actor')
        result = cursor.fetchall()
        for data in result:
                print(data[0], data[1])
#       print data
                cursor.close()
                con.close()

except psycopg2.DatabaseError, e:
                print "I am unable to connect to the database"
                sys.exit(1)

finally:
        if con:
                con.close()
Share Button

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.