mysql - 事务和提交

标签 mysql transactions

哪个代码适合交易? 我需要检查提交的查询结果吗?

这段代码没有结果

mysql_query("BEGIN");
$strSQL = "INSERT INTO table values";
$strSQL .="('','a')";
$objQuery1 = mysql_query($strSQL);
$strSQL = "INSERT INTO table values";
$strSQL .="('','a','a')";
$objQuery2 = mysql_query($strSQL);
if(($objQuery1) and ($objQuery2))
{
mysql_query("COMMIT");
echo "Save Done.";
}
else
{
mysql_query("ROLLBACK");
}
?>

此代码结果 1 插入。为什么?不会提交识别错误?

  <?php
    mysql_query("BEGIN");
    $strSQL = "INSERT INTO table values";
    $strSQL .="('','a')";
    $objQuery1 = mysql_query($strSQL);
    $strSQL = "INSERT INTO table values";
    $strSQL .="('','a','a')";
    $objQuery2 = mysql_query($strSQL);
    mysql_query("COMMIT");
    ?>

最佳答案

可能会让您感到困惑的是,在 MySQL 中发出 commit 不会转换为 rollback [everything] 错误。相反,它转化为:commit 没有错误的内容。

mysql> create table test (id int unique);
Query OK, 0 rows affected (0.10 sec)

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> insert into test values (1);
Query OK, 1 row affected (0.00 sec)

mysql> insert into test values (1);
ERROR 1062 (23000): Duplicate entry '1' for key 'id'
mysql> commit;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from test;
+------+
| id   |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

相比之下,在 Postgres 中:

test=# create table test (id int unique);
NOTICE:  CREATE TABLE / UNIQUE will create implicit index "test_id_key" for table "test"
CREATE TABLE
test=# begin;
BEGIN
test=# insert into test values (1);
INSERT 0 1
test=# insert into test values (1);
ERROR:  duplicate key value violates unique constraint "test_id_key"
DETAIL:  Key (id)=(1) already exists.
test=# commit;
ROLLBACK
test=# select * from test;
 id 
----
(0 rows)

另外,请考虑改用 mysqli。它直接支持这种东西:

http://www.php.net/manual/en/mysqli.commit.php

或 PDO:

http://php.net/manual/en/pdo.commit.php

使用 PDO,正确的序列如下所示:

try {
  # begin transaction
  # do stuff
  # commit
} catch (Exception $e) {
  # rollback
}

使用 MySQLi,您也可以使用 or 运算符使其表现得像上面那样:

try {
  # begin transaction
  # do stuff or throw new Exception;
  # commit
} catch (Exception $e) {
  # rollback
}

关于mysql - 事务和提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6477067/

相关文章:

java - 获取 org.hibernate.exception.JDBCConnectionException : could not execute query in Spring application after some time of application working fine

spring - @Transactional(readOnly = true) 导致 LazyInitializationException

PHP pdo : prepare() vs transactions

java - JMS-分布式事务

php - mysql_insert_id 不工作

mysql - 新安装的 python 3.7/django 2.2.1 无法识别已安装 mysqlclient

php - PHP 中 WHERE 后的多列?

java - Springs @Transactional 仅适用于代理

php - 在 MySql 中查找挂起的锁或事务

mysql - { : task 1 failed - "could not find function "dbGetQuery""中的 FOREACH 循环错误