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 http://www.initd.org

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

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

  • And install the extension
    $ sudo python setup.py install

  • Create a simple script
    $ vim pypgsql.py


    import psycopg2

    try:
        conn = psycopg2.connect("dbname='test' user='jayant' host='localhost' password='secret'")
    except:
        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 pypgsql.py file.

  • And finally run the script
    $ python pypgsql.py

    Output:

    Show me the databases

      template1
      template0
      postgres
      test

No comments: