Python MySql查询静默失败
我有一个MySql数据库(使用stock Docker映像运行),它包含一个定义如下的表:Python MySql查询静默失败,python,mysql,Python,Mysql,我有一个MySql数据库(使用stock Docker映像运行),它包含一个定义如下的表: CREATE TABLE `Edits` ( `id` int(11) NOT NULL AUTO_INCREMENT, `context` varchar(255) NOT NULL, `field` varchar(255) NOT NULL, `value` text, `username` varchar(255) DEFAULT NULL, `requested` dat
CREATE TABLE `Edits` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`context` varchar(255) NOT NULL,
`field` varchar(255) NOT NULL,
`value` text,
`username` varchar(255) DEFAULT NULL,
`requested` datetime DEFAULT NULL,
PRIMARY KEY (`id`,`context`,`field`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1
import contextlib
import MySQLdb
mysql = MySQLdb.connect(host = 'host', db = 'db')
def _cursor():
mysql.ping(True)
return contextlib.closing(mysql.cursor())
def _exec(sql, params = None):
with _cursor() as c:
c.execute(sql, params)
def save_edits(id, context, field, value, username):
return _exec('REPLACE INTO Edits SET id = %(id)s, context = %(context)s,
field = %(field)s, value = %(value)s, username = %(username)s,
requested = UTC_TIMESTAMP()', {
'id': id,
'context': context,
'field': field,
'value': value,
'username': username,
})
我在WSGI应用程序中连接到它,我的连接代码如下所示:
CREATE TABLE `Edits` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`context` varchar(255) NOT NULL,
`field` varchar(255) NOT NULL,
`value` text,
`username` varchar(255) DEFAULT NULL,
`requested` datetime DEFAULT NULL,
PRIMARY KEY (`id`,`context`,`field`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1
import contextlib
import MySQLdb
mysql = MySQLdb.connect(host = 'host', db = 'db')
def _cursor():
mysql.ping(True)
return contextlib.closing(mysql.cursor())
def _exec(sql, params = None):
with _cursor() as c:
c.execute(sql, params)
def save_edits(id, context, field, value, username):
return _exec('REPLACE INTO Edits SET id = %(id)s, context = %(context)s,
field = %(field)s, value = %(value)s, username = %(username)s,
requested = UTC_TIMESTAMP()', {
'id': id,
'context': context,
'field': field,
'value': value,
'username': username,
})
当我调用save\u edits
函数时,它不会抛出异常,但无法更新数据库。此外,尝试将查询REPLACE运行到编辑集id=1,context='x',field='y',value='z',username='foo',requested=UTC_TIMESTAMP()代码>通过mysql
shell之后失败,出现错误1205(HY000):超过锁等待超时;尝试重新启动事务
错误。但是,如果我等待大约5分钟,错误就会消失,我可以再次对MySql数据库运行REPLACE-INTO
查询
发生什么事了?如何修复此错误?事实证明,默认情况下,autocommit
为false
,在不关闭连接的情况下关闭光标将保持事务打开。我将方法更改为:
def _exec(sql, params = None):
with _cursor() as c:
c.execute(sql, params)
mysql.commit()
这就解决了问题。是否需要显式提交更新?我要尝试的第一件事是运行查询SET SQL\u SAFE\u update=0代码>有时安全更新会捕获内容,不允许您更新