python - 为什么 Python/Django 不会在 Mysql : ERROR 1205 (HY000): Lock wait timeout exceeded 上引发异常

标签 python mysql django exception locking

我正在通过 python/django 在我的 MySQL 数据库中测试锁定。

我有一张 table ,我正在测试:

CREATE TABLE `test` (
  `id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into test (id) values (1), (2);
commit;

我有 3 个 session : - 2个mysql控制台 - 1 个 Django View

控制台 1:

mysql> begin; select t.id from test as where id = 1 t FOR UPDATE;
Query OK, 0 rows affected (0.00 sec)

+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.00 sec)

控制台 2:

mysql> set @@session.innodb_lock_wait_timeout = 1;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> select t.id from test as t FOR UPDATE;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> select t.id from test as t where id = 1 FOR UPDATE;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

Django View :

@db.transaction.commit_manually
def Test(request):
  c = db.connection.cursor()
  c.execute('set @@session.innodb_lock_wait_timeout = 1')
  c.execute('select t.id from test as t FOR UPDATE')
  logging.error(c.fetchall())
  c.execute('select t.id from test as t where id = 1 FOR UPDATE')
  logging.error(c.fetchall())
  db.transaction.rollback()

  return render_to_response(
      'test.html',
      context_instance=template.RequestContext(request, {})
      )

调用此 View 后,我预计会出现异常,但什么也没有发生,它返回一个空结果集。

有什么想法吗?

版本:

  • python :2.7.3
  • Django :1.4.3
  • MySQL:5.5

谢谢,丹尼尔

最佳答案

You are using a transaction; autocommit does not disable transactions, it just makes them automatically commit at the end of the statement.

What is happening is, some other thread is holding a record lock on some record for too long, and your thread is being timed out.

Source: Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

您应该通过设置 innodb_lock_wait_timeout=50(默认值)或将其设置为更高的值并重新启动 MySQL 来增加 InnoDB 的锁定等待超时值。

关于python - 为什么 Python/Django 不会在 Mysql : ERROR 1205 (HY000): Lock wait timeout exceeded 上引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15784430/

相关文章:

database - 加载大量初始数据时出现 MemoryError

python - 在Pygame中沿光标方向绘制无限长度的线

mysql - 查找组中特定行的两个日期列之间的平均值

python - 按索引值将 pandas Series 拆分为连续的 block

mysql - 合并同一个表中的 2 个字段?

mysql - 选择具有自定义条件的数据

python - 值错误 : Field 'id' expected a number but got 'super' . [04/4/2020 18:15:11] "GET/super_user HTTP/1.1"500 132224

python - 如何在包含数据的数据库上激活/使用 django-mptt?

python - Pandas 无格式导出到excel

Python对象绑定(bind)方法