Quick questions about globals and database connections
Joel Goldstick
joel.goldstick at gmail.com
Wed Apr 5 11:17:12 EDT 2017
On Wed, Apr 5, 2017 at 11:09 AM, Python <python at example.invalid> wrote:
> 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()
>> -------------------------------------------------------------
>>
>>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
You may have an indentation problem that isn't apparent in your code
pasted here. Are you sure that dbconnect always returns something?
--
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
More information about the Python-list
mailing list