Quick questions about globals and database connections

Python python at example.invalid
Wed Apr 5 11:09:38 EDT 2017


Le 05/04/2017 à 16:54, DFS a écrit :
> 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   return conn.cursor()

> 9
> 10 def updatedb(dbtype):

11   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()
> -------------------------------------------------------------
>
>




More information about the Python-list mailing list