【发布时间】:2019-07-08 10:05:49
【问题描述】:
这里我创建了两个 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)
编辑 以下是我使用的无效执行函数。这使用了一个公共连接,每次都检查无条件。
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
【问题讨论】:
-
如果您有两个单独的数据库实例,例如您的情况下的 a 和 b,每当您在其中调用
get_overview函数时,您需要通过连接到数据库来更新您的 SQL 连接再次获取最新值。 -
但是它访问的是同一个数据库,所以为什么我需要更新 sql 连接
-
您的代码是在更新值时立即提交更改还是稍后提交?如果是后者,那么在默认隔离级别配置下,其他事务无法看到对数据的未决(未提交)更改。您要么必须提前提交更改(推荐选项),要么需要更改隔离级别以读取未提交。我不会做后者,因为它可能会产生不良后果,例如看到数据库的不一致状态。
-
@Saeed 请阅读有关事务隔离级别以及如何设置它们而不是发布此类错误建议的信息....
标签: python mysql connection