Friday, May 23, 2008

python postgresql connectivity

It is sweet and simple. Got it running in 2 minutes...

  • Download psycopg 2.0 (yup that's the name) from

  • Extract the library
    $ tar -xvzf psycopg2-2.0.7.tar.gz

  • Build the extension
    $ cd psycopg2-2.0.7/
    $ python build

  • And install the extension
    $ sudo python install

  • Create a simple script
    $ vim

    import psycopg2

        conn = psycopg2.connect("dbname='test' user='jayant' host='localhost' password='secret'")
        print "unable to connect to db"

    cur = conn.cursor()
    cur.execute("""select datname from pg_database""")
    rows = cur.fetchall()

    print "\nShow me the databases\n"
    for row in rows:
        print " ", row[0]

    Save the file.

  • And finally run the script
    $ python


    Show me the databases


No comments: