Quick questions about globals and database connections
John Gordon
gordon at panix.com
Wed Apr 5 11:22:02 EDT 2017
In <oc308v$s18$2 at dont-email.me> DFS <nospam at dfs.com> writes:
> 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.
Instead of trying to make db global, dbconnect() can return the db object:
def dbconnect(dbtype):
if dbtype == "sqlite":
conn = sqlite3.connect(cstr)
elif dbtype == "postgres":
conn = psycopg2.connect(cstr)
return conn.cursor()
def updatedb(dbtype):
db = dbconnect(dbtype)
db.execute("DML code")
print "updated " + dbtype
'close connection
It would probably be even better to return conn, as that would allow
updatedb() to call conn.disconnect().
--
John Gordon A is for Amy, who fell down the stairs
gordon at panix.com B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
More information about the Python-list
mailing list