简体   繁体   English

MySQL的:交易? 插入和更新

[英]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 : 基本上,通过交易,您可以:

  • Start a transaction 开始交易
  • Do the first query 进行第一个查询
  • If it succeeds, do the second query 如果成功,请执行第二个查询
    • If it succeed, commit the transaction 如果成功,则提交事务
    • Else, rollback the transaction -- cancelling both queries that correspond to that transaction. 否则,回滚事务-取消与该事务相对应的两个查询。


If working with mysql_* function, you'll have to : 如果使用mysql_*函数,则必须:

  • Start the transaction, with a START TRANSACTION query 使用START TRANSACTION查询START TRANSACTION
  • Do your queries 进行查询
  • Depending on the result of those queries, either do a COMMIT or a ROLLBACK query. 根据这些查询的结果,执行COMMITROLLBACK查询。

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 ,您可以使用:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM