[DB-SIG] Database connections don't stay alive

Matthew Nuzum mattnuzum at gmail.com
Fri Jun 3 19:42:16 CEST 2005


On 6/3/05, Olli Rajala <olli.rajala at gmail.com> wrote:
> from pyPgSQL import PgSQL
> def connectDB():
>     try:
>         db = PgSQL.connect(host='localhost', database='pictures',
> user='user', password='passwd')
>         return db.cursor()
>     except:
>         print "Error"
> 
> cursor = connectDB()
> cursor.execute("SELECT * FROM categories")
> print cursor.fetchall()
> 
> The result is:
> 
> Traceback (most recent call last):
>   File "test.py", line 23, in ?
>     cursor.execute("SELECT * FROM categories")
>   File "/usr/lib/python2.4/site-packages/pyPgSQL/PgSQL.py", line 2992,
> in execute
>     raise InterfaceError, "execute failed - the cursor is closed."
> libpq.InterfaceError: execute failed - the cursor is closed.
> 
> So, what's the solution for this? I saw somewhere some mentions about
> 'connection pooling', what's that and how I'm supposed to use that?
> 

Connection pooling allows several programs to share connections to a
database. Your first step should be to get things working and then, if
you start killing your db server look into pooling.

Here's how I connect to a postgres db and use it. It may not be the
most modern way, but it works fine:

import pgdb
try:
    db = pgdb.connect(dsn="hostname:dbname", user="username", password="pwd")
except:
    print >> sys.stderr, "Problem making database connection... Try again"

cursor = db.cursor()
sql = "select * from table"
cursor.execute(sql)

while (1):
      row = cursor.fetchone()
      if row == None: break
      print row

cursor.close()
db.close()


-- 
Matthew Nuzum
www.bearfruit.org


More information about the DB-SIG mailing list