Wednesday, January 5, 2011

Connecting to PostgreSQL with Python and Psycopg2

Basic syntax for making a database connection, executing and retrieving data:



import psycopg2 as pg
# create database connection
try:
   conn = pg.connect("dbname='template1' user='dbuser' host='localhost' password='dbpass'")
except:
   print "Unable to connect to database"
# create database cursor
cur = conn.cursor()
# execute SQL and fetch results
cur.execute("""SELECT datname from pg_database""")
rows = cur.fetchall()
print "\nShow database results:\n"
for row in rows:
   print row[0]

No comments:

Post a Comment