为什么Python / Django不会在Mysql上引发异常:ERROR 1205(HY000):超出锁定等待超时

时间:2013-04-03 10:06:21

标签: python mysql django exception-handling locking

我正在测试从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 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观点:

@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

谢谢,丹尼尔

1 个答案:

答案 0 :(得分:0)

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. Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

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