MySQL 事务
时间:2021-07-01 10:21:17
帮助过:6人阅读
use RUNOOB;
Database changed
mysql> CREATE TABLE runoob_transaction_test( id
int(
5)) engine
=innodb; # 创建数据表
Query OK, 0 rows affected (
0.04 sec)
mysql> select * from runoob_transaction_test;
Empty set (
0.01 sec)
mysql> begin; # 开始事务
Query OK, 0 rows affected (
0.00 sec)
mysql> insert into runoob_transaction_test value(
5);
Query OK, 1 rows affected (
0.01 sec)
mysql> insert into runoob_transaction_test value(
6);
Query OK, 1 rows affected (
0.00 sec)
mysql> commit; # 提交事务
Query OK, 0 rows affected (
0.01 sec)
mysql> select * from runoob_transaction_test;
+------+
| id
|
+------+
| 5 |
| 6 |
+------+
2 rows
in set (
0.01 sec)
mysql> begin; # 开始事务
Query OK, 0 rows affected (
0.00 sec)
mysql> insert into runoob_transaction_test
values(
7);
Query OK, 1 rows affected (
0.00 sec)
mysql> rollback; # 回滚
Query OK, 0 rows affected (
0.00 sec)
mysql> select * from runoob_transaction_test; # 因为回滚所以数据没有插入
+------+
| id
|
+------+
| 5 |
| 6 |
+------+
2 rows
in set (
0.01 sec)
mysql>
PHP中使用事务实例
MySQL ORDER BY 测试:
<?php
$dbhost = ‘localhost:3306‘; // mysql服务器主机地址
$dbuser = ‘root‘; // mysql用户名
$dbpass = ‘123456‘; // mysql用户名密码
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die(‘连接失败: ‘ . mysqli_error($conn));
}
// 设置编码,防止中文乱码
mysqli_query($conn, "set names utf8");
mysqli_select_db( $conn, ‘RUNOOB‘ );
mysqli_query($conn, "SET AUTOCOMMIT=0"); // 设置为不自动提交,因为MYSQL默认立即执行
mysqli_begin_transaction($conn); // 开始事务定义
if(!mysqli_query($conn, "insert into runoob_transaction_test (id) values(8)"))
{
mysqli_query($conn, "ROLLBACK"); // 判断当执行失败时回滚
}
if(!mysqli_query($conn, "insert into runoob_transaction_test (id) values(9)"))
{
mysqli_query($conn, "ROLLBACK"); // 判断执行失败时回滚
}
mysqli_commit($conn); //执行事务
mysqli_close($conn);
?>
MySQL 事务
标签:tran 两种 结果 connect 异常 ext rollback use block