[英]mysql: transaction? insert and update
I need to do 2 query. 我需要做2查询。
Basically it's a 基本上是
mysql_query("INSERT INTO table ($value1,$value2)");
and 和
mysql_query("UPDATE table2 SET field1 = '$value1', field2 = '$value2'");
I think I can simply do a 我想我可以做一个
if (mysql_query("INSERT ...") !== false) {
mysql_query("UPDATE ...");
}
In this case should I use a transaction? 在这种情况下,我应该使用交易吗? And how should I use it?
我应该如何使用它?
Or can i leave that simple if? 还是我可以这么简单吗?
Thanks 谢谢
You will generally use transactions if you want some "all or nothing" behavior. 如果您想要某些“全有或全无”行为,通常将使用事务。
Basically, with transactions, you can : 基本上,通过交易,您可以:
If working with mysql_*
function, you'll have to : 如果使用
mysql_*
函数,则必须:
START TRANSACTION
query START TRANSACTION
查询START TRANSACTION
COMMIT
or a ROLLBACK
query. COMMIT
或ROLLBACK
查询。 To detect whether a query succeeded or not, you can indeed check the return value of mysql_query()
: it will return false
in case of an error. 为了检测查询是否成功,您确实可以检查
mysql_query()
的返回值:如果发生错误,它将返回false
。
Note : MySQL is the old extension -- and doesn't have functions to deal with transactions ; 注意:MySQL是旧的扩展-它没有处理事务的功能; which means you have to deal with them as regular queries.
这意味着您必须将它们作为常规查询来处理。
Working with MySQLi , you could use : 使用MySQLi ,您可以使用:
mysqli::autocommit()
to disable autocommit mysqli::autocommit()
禁用自动提交 mysqli::commit()
or mysqli::rollback()
mysqli::commit()
或mysqli::rollback()
For insert and updates MySQL has a good, alternative solution - "ON DUPLICATE KEY UPDATE". 对于插入和更新,MySQL有一个很好的替代解决方案-“ ON DUPLICATE KEY UPDATE”。 It does what you want safely in a single query:
它可以在单个查询中安全地执行您想要的操作:
INSERT .... ON DUPLICATE KEY UPDATE
(also the key must be set as unique in this scenario) (在这种情况下,密钥也必须设置为唯一)
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.