这里我创建了两个到同一个数据库的 MySQL 连接。
当一个连接更新类中存在的数据库时,另一个连接无法获取更改。这是我的代码
tm():处理连接、执行查询和获取数据库概览的数据库类
class ClassB():
b = None
def __init__(self):
self.b = database()
def get_overview_for_b(self):
self.b.mark_invalid('9')
self.b.mark_invalid('8')
b_str = ''.join(map(str, self.b.get_overview()))
print("Getting the overview of b" + b_str)
# initializing class B
inside_class_b = ClassB()
# initializing class for A
a = database()
# get database overview for A
astart = a.get_overview()
a_str = ''.join(map(str, astart))
print("Getting the overview of a before testing" + a_str)
# updating database and get database overview for B
inside_class_b.get_overview_for_b()
# get another overview for A
aend = a.get_overview()
a_str = ''.join(map(str, aend))
print("Getting the overview of a after testing" + a_str)
# The final overview of both A and B should be same, but isn't
实际输出
Getting the overview of a before testing('PENDING', 2)
Getting the overview of b('INVALID', 2)
Getting the overview of a after testing('PENDING', 2)
预期输出
Getting the overview of a before testing('PENDING', 2)
Getting the overview of b('INVALID', 2)
Getting the overview of a after testing('INVALID', 2)
虽然我刚刚尝试过,但如果我使用“a”来更新“b”,则会得到更新后的值。
class ClassB():
b = None
def __init__(self):
self.b = database()
def get_overview_for_b(self):
b_str = ''.join(map(str, self.b.get_overview()))
print("Getting the overview of b" + b_str)
# initializing class B
inside_class_b = ClassB()
# initializing class for A
a = database()
# get database overview for A
astart = a.get_overview()
a_str = ''.join(map(str, astart))
print("Getting the overview of a before testing" + a_str)
# updating using 'a'
a.mark_invalid('9')
a.mark_invalid('8')
# get database overview for B
inside_class_b.get_overview_for_b()
# get another overview for A
aend = a.get_overview()
a_str = ''.join(map(str, aend))
print("Getting the overview of a after testing" + a_str)
预期输出和实际输出相同
Getting the overview of a before testing('PENDING', 2)
Getting the overview of b('INVALID', 2)
Getting the overview of a after testing('INVALID', 2)
编辑 下面是我使用的execute函数无效。这使用了一个公共(public)连接,每次都检查 None 条件。
def execute(self, statement, attributes):
"""
Execute a query for the database
:arg:
statement - Statement to be executed.
attributes - Attributes supporting the statement.
"""
if self._db_connection is None:
self.connect()
cursor = self._db_connection.cursor()
cursor.execute(statement, attributes)
self._db_connection.commit()
t = cursor.rowcount
cursor.close()
del cursor
return t
最佳答案
在 get_overview() 中没有提交命令。添加 connection.commit() 后,代码按预期工作。
问题已解决。 感谢所有帮助过我的人。
关于python - python中mysql多连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56932623/