Python 的“全局”变量没有全局范围。它们是模块范围的变量。所以不同模块中的同名全局变量不是同一个变量。
我认为您可能正在关闭mainlib.db
然后设置mytestcode.db
为新数据库。您的所有其余代码当然会继续使用mainlib.db
,现在已关闭。
试试mainlib.db = MySQLdb.connect(...)
, 和游标一样。直接修改另一个模块的变量是丑陋的,但它可以像你期望的那样工作。
另一种方法是引入一种配置如何mainlib
打开数据库的方法。例如,你可以有这样的函数mainlib
:
db = None
dbname = None
cursor = None
def connectdb(name = None):
"""
Set up the global database connection and cursor, if it isn't already.
Omit 'name' when the caller doesn't care what database is used,
and is happy to accept whatever database is already connected or
connect to a default database.
Since there cannot be multiple global databases, an exception is thrown
if 'name' is specified, the global connection already exists, and the
names don't match.
"""
global db, dbname, cursor
if db is None:
if name is None:
name = 'MyDatabase'
db = MySQLdb.connect(host='localhost', user='admin', password='admin', db=name)
dbname = name
cursor = db.cursor()
elif name not in (None, dbname):
raise Exception('cannot connect to the specified db: the global connection already exists and connects to a different db')
现在,在您的普通程序中(不是在每个模块中,只是在顶层),您mainlib.connectdb()
在导入mainlib
. 在您调用的测试代码mainlib.connectdb('TestDatabase')
中。
或者,您可以connectdb
返回游标和/或连接对象,这样,使用全局数据库的所有内容都可以通过此函数。
就个人而言,我根本不喜欢使用全局变量——我将拥有一个创建数据库连接的函数,并将该数据库作为参数传递给任何需要它的东西。但是,我意识到在这方面的口味各不相同。