Python ->
Connect to PostgreSQL database from Python

Simple example: Connect to PostgreSQL database from python and print table rows.

# ------------------------------------------------
# PostgreSQL simple test
# select from table and print cursor rows
# ------------------------------------------------

import sys
import psycopg2

con = None

try:
  print
  print 'This is postgres db test'
  print 'print table: emp'
  print '------------------------'
  print

  con = psycopg2.connect(database="demo", user="postgres", password="12345", host="localhost", port="5433")

  cur = con.cursor()
  cur.execute("SELECT * FROM emp;")

  rows = cur.fetchall()

  for row in rows:
   print row

  print
  print '------------------------'
  print 'end of test.'

except psycopg2.DatabaseError, e:
  print 'Error %s' % e
  sys.exit(1)

finally:

  if con:
  con.close()




sqlexamples.info