exception handling; python program that interacts with postgresql db

Tim Roberts timr at probo.com
Fri Aug 4 02:10:36 EDT 2006


"damacy" <wegein at gmail.com> wrote:

>hi, there. i have this question which might sound quite stupid to some
>people, but here we go anyway.
>
>i have written a python program which interacts with a postgresql
>database. what it does is simply drops an existing database called
>'mytempdb'.
>
>the code looks like below;
>
>link = subprocess.Popen(command, stdin = subprocess.PIPE, stdout =
>subprocess.PIPE, shell = True)
>link.communicate(password)
>link.wait()
>
>where command looks like "psql -h 127.0.0.1 -U postgres -W -f filename"
>and
>filename is the name of the file which contains a single SQL command
>which is "drop database mytempdb".

hiaips is right.  The right way to do this is to use a Postgres module.
psycopg is my favorite, but there are several alternatives.

    import psycopg
    db = psycopg.connect(
        "dbname=template1 user=postgres password=%s" % password )
    c = db.cursor()
    c.execute( "drop database mytempdb;" )
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list