scope question

Hans Nowak wurmy at earthlink.net
Thu Nov 15 10:57:53 EST 2001


Choco wrote:
> 
> I am re-working a program to abstract some elements of a set of cgi's into
> a shared library.  One thing I'm looking to abstract is the database
> connection code.  To do so, I've created a connect() method and a close()
> method.  The connect() method returns a cursor which the cgi then uses to
> execute a series of sql statements.  To close out the cursor and the
> database connection the cursor is passed to the close method.  How do I get
> this to work?  I find that I cannot simply do this:
> 
> def close(cursor):
>         cursor.close()
>         db.close()
> 
> This fails with a NameError: global name 'db' is not defined.
> 
> I'm searching for the solution to this at the moment, but thought I'd post
> here to see if anyone had any tips.

How about passing both the database and the cursor to the close
function?

def close(cursor, db):
    cursor.close()
    db.close()

Since I don't know your code, I don't know if this is possible in your
situation.
You say that connect() and close() are methods... of what? Of the
database object?
Where does db come from?

Normally I would connect to a database like this:

db = <databasemodule>.connect(...)
c = db.cursor()
c.execute(...some SQL...)
c.close()
db.close()

I don't know much about the database API, but under at least one
database module
I know (mssql.pyd) it's possible to get the database through the cursor:

  db = cursor._owner
  db.close()

HTH,

--Hans



More information about the Python-list mailing list