这是我的MySQL类,在需要SQL连接的多个其他类之间共享:
class mysqlAssist():
def __init__(self):
self.con = MySQLdb.connect("localhost","user","pass","DB",3306, charset="utf8")
self.con.autocommit(True)
@contextmanager
def cursor(self, *args, **kwargs):
c = self.con.cursor( *args, **kwargs)
try:
yield c
finally:
c.close()
def fetchOne(self, _sql):
with self.cursor() as c:
try:
c.execute(_sql)
return c.fetchone()
except (MySQLdb.Error, MySQLdb.Warning) as e:
print(e)
def fetchAll(self, _sql):
with self.cursor( MySQLdb.cursors.DictCursor ) as c:
try:
c.execute(_sql)
return c.fetchall()
except (MySQLdb.Error, MySQLdb.Warning) as e:
print(e)
Mymain模块同时执行以下两个SQL查询:
正在调用mysqlAssist.fetchOne:
SELECT `start_time`, `stop_time`, `AHC_DAY` FROM `_management` WHERE `_active` = '1'
正在调用mysqlAssist.fetchAll:
SELECT _id, _desc, _show_type, _web_manage, _lastevent, _lastevent=max_lastevent
AS _latest FROM `_setup` CROSS JOIN (SELECT MAX(_lastevent) as max_lastevent FROM _setup) m
第二个查询结果如下所示:
+---------+-------------------+----------------+-----------------+----------------+-------------+
| _id | _desc | _show_type | _web_manage | _lastevent | _latest |
+---------+-------------------+----------------+-----------------+----------------+-------------+
| here>11 | A | 1 | 1 | 1633107217 | 0 |
| 6 | B | 1 | 0 | 1633168302 | 0 |
| 12 | C | 0 | 0 | 1633169804 | 1 |
| 16 | D | 0 | 1 | 1632480486 | 0 |
| 19 | E | 0 | 0 | 1632549333 | 0 |
| 26 | F | 0 | 0 | 1631868026 | 0 |
| 25 | G | 1 | 0 | 1633168303 | 0 |
| 27 | H | 1 | 1 | 1632992896 | 0 |
+---------+-------------------+----------------+-----------------+----------------+-------------+
现在的问题是:第一个查询很少也偶尔会返回第二个查询的结果,具体值为:11
,这是第二个查询的第一行和第一列结果。问题的证据是,我的回溯显示了以下错误,因为它预期的结果(日期)与纯数字完全不同:ERROR - time data '11' does not match format '%H:%M:%S'
,因此这确实不是数据库的预期结果
那么,结果中会出现数据不匹配,这是怎么回事呢?这是因为第二个查询使用了MySQLdb.cursors.DictCursor
游标类型,还是CROSS JOIN
或者当我同时进行两个查询时cursor
存在竞争?我应该实现一些cursor
锁或队列吗?如何实现
MySQL连接一次只能有一个游标-一个活动查询。但是连接不是很昂贵,所以您可以为需要并发运行的每个查询使用单独的连接
相关问题 更多 >
编程相关推荐