How to lock tables with codeigniter?

假装没事ソ 提交于 2020-01-15 03:58:21

问题


I have to run this sql routine in a model:

$this->db->query('LOCK TABLE orders WRITE');
$this->db->query('TRUNCATE TABLE orders');
$this->db->query('INSERT INTO orders SELECT * FROM orders_tmp');
$this->db->query('UNLOCK TABLES');

but I get this error:

Error Number: 1192
Impossible to execute the requested command: tables under lock or transaction running
TRUNCATE TABLE orders

I use MyISAM as DB engine on this table.

Could you please help me?


回答1:


To perform many INSERT and SELECT operations on a table real_table when concurrent inserts are not possible, you can insert rows into a temporary table temp_table and update the real table with the rows from the temporary table periodically. This can be done with the following code:

mysql> LOCK TABLES real_table WRITE, temp_table WRITE;

Kindly ask if it not worked for you.




回答2:


try this

$this->db->query('TRUNCATE TABLE orders');
$this->db->query('LOCK TABLE orders WRITE');
$this->db->query('INSERT INTO orders SELECT * FROM orders_tmp');
$this->db->query('UNLOCK TABLES');



回答3:


You're required to acquire a lock for all tables in your query, not just the table you're writing to. So in your case you also need a read lock on orders_tmp.

From the docs:

A session that requires locks must acquire all the locks that it needs in a single LOCK TABLES statement. While the locks thus obtained are held, the session can access only the locked tables.

Docs here: https://dev.mysql.com/doc/refman/5.5/en/lock-tables.html

Cheers



来源:https://stackoverflow.com/questions/11541171/how-to-lock-tables-with-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!