Quick questions about globals and database connections

Dan Sommers dan at tombstonezero.net
Wed Apr 5 11:31:37 EDT 2017


On Wed, 05 Apr 2017 10:54:29 -0400, DFS wrote:

> I have identical databases in sqlite and postgres.  I want to run the 
> same code against them, but am having a small issue.
> 
> Current code below throws the dreaded:
> 
> NameError: global name 'db' is not defined
> 
> on line 12
> 
> How do I fix it?  I want to keep dbconnect() as a separate function.
> 
> Thanks.
> 
> -------------------------------------------------------------
> 1 import sqlite3, psycopg2
> 2
> 3 def dbconnect(dbtype):
> 4   if dbtype == "sqlite":
> 5     conn = sqlite3.connect(cstr)
> 6   elif dbtype == "postgres":
> 7     conn = psycopg2.connect(cstr)
> 8   db = conn.cursor()

This line just sets db locally to dbconnect.

You'll have to return it in order to use it elsewhere.

Add a line like this:

    return db

> 9	
> 10 def updatedb(dbtype):
> 11   dbconnect(dbtype)

And then use the return value from dbconnect to create a new db locally
to updatedb:

    db = dbconnect(dbtype)

> 12   db.execute("DML code")
> 13   print "updated " + dbtype
> 14   'close connection
> 
> 15 def main():
> 16   updatedb('sqlite')
> 17   updatedb('postgres')
> 18
> 19 if __name__ == "__main__":
> 20   main()
> -------------------------------------------------------------

HTH,
Dan



More information about the Python-list mailing list