【问题标题】:Why Python/Django does not raise exception on Mysql: ERROR 1205 (HY000): Lock wait timeout exceeded为什么 Python/Django 不会在 Mysql 上引发异常:ERROR 1205 (HY000): Lock wait timeout exceeded
【发布时间】:2013-03-24 22:43:21
【问题描述】:

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

我有一张桌子,我正在测试:

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 节课: - 2个mysql控制台 - 1 个 Django 视图

控制台 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 视图:

@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, {})
      )

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

有什么想法吗?

版本:

  • Python:2.7.3
  • Django:1.4.3
  • MySQL:5.5

谢谢,丹尼尔

【问题讨论】:

  • 您是否遇到其他错误,例如外键错误?
  • 是的,我遇到了这样的异常。有趣的是,如果我运行 'select t.id from test as t FOR UPDATE' 也不例外,但如果我只运行 'select t.id from test as t where id = 1 FOR UPDATE' 那么我得到数据库错误。所以现在我完全糊涂了:)

标签: python mysql django exception-handling locking


【解决方案1】:

您正在使用交易; autocommit 不会禁用事务,它只是让它们在语句结束时自动提交。

发生的情况是,某个其他线程在某个记录上持有记录锁的时间过长,而您的线程正在超时。

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

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

【讨论】:

    猜你喜欢
    • 2016-09-13
    • 2018-08-30
    • 2011-06-14
    • 1970-01-01
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多