MySQL 8 教程

MySQL - 主页 MySQL - 简介 MySQL - 功能 MySQL - 版本 MySQL - 变量 MySQL - 安装 MySQL - 管理 MySQL - PHP 语法 MySQL - Node.js 语法 MySQL - Java 语法 MySQL - Python 语法 MySQL - 连接 MySQL - Workbench

MySQL 8 数据库

MySQL - 创建数据库 MySQL - 删除数据库 MySQL - 选择数据库 MySQL - 显示数据库 MySQL - 复制数据库 MySQL - 数据库导出 MySQL - 数据库导入 MySQL - 数据库信息

MySQL 8 用户

MySQL - 创建用户 MySQL - 删除用户 MySQL - 显示用户 MySQL - 更改密码 MySQL - 授予权限 MySQL - 显示权限 MySQL - 撤销权限 MySQL - 锁定用户账户 MySQL - 解锁用户账户

MySQL 8 表

MySQL - 创建表 MySQL - 显示表 MySQL - 修改表 MySQL - 重命名表 MySQL - 克隆表 MySQL - 截断表 MySQL - 临时表 MySQL - 修复表 MySQL - 描述表 MySQL - 添加/删除列 MySQL - 显示列 MySQL - 重命名列 MySQL - 表锁定 MySQL - 删除表 MySQL - 派生表

MySQL 8 查询

MySQL - 查询 MySQL - 约束 MySQL - INSERT 插入查询 MySQL - SELECT 查询 MySQL - UPDATE 更新查询 MySQL - DELETE删除查询 MySQL - REPLACE 替换查询 MySQL - 忽略插入 MySQL - 重复键更新时插入 MySQL - 插入到另一个表语句

MySQL 8 视图

MySQL - 创建视图 MySQL - 更新视图 MySQL - 删除视图 MySQL - 重命名视图

MySQL 8 索引

MySQL - 索引 MySQL - 创建索引 MySQL - 删除索引 MySQL - 显示索引 MySQL - 唯一索引 MySQL - 聚集索引 MySQL - 非聚集索引

MySQL 运算符和子句

MySQL - Where 子句 MySQL - Limit 子句 MySQL - Distinct 子句 MySQL - Order By 子句 MySQL - Group By 子句 MySQL - Having 子句 MySQL - AND 运算符 MySQL - OR 或运算符 MySQL - LIKE 运算符 MySQL - IN 运算符 MySQL - ANY 运算符 MySQL - Exists 运算符 MySQL - NOT 运算符 MySQL - NOT EQUAL 运算符 MySQL - IS NULL 运算符 MySQL - IS NOT NULL 运算符 MySQL - Between 运算符 MySQL - UNION 运算符 MySQL - UNION 与 UNION ALL MySQL - MINUS 运算符 MySQL - INTERSECT 运算符 MySQL - INTERVAL 运算符

MySQL 连接

MySQL - 使用连接 MySQL - Inner Join 内连接 MySQL - LEFT JOIN 左连接 MySQL - RIGHT JOIN 右连接 MySQL - CROSS JOIN 交叉连接 MySQL - 全连接 MySQL - 自连接 MySQL - Delete Join 删除连接 MySQL - UPDATE JOIN 更新连接 MySQL - 联合 vs 连接

MySQL 键

MySQL - UNIQUE 唯一键 MySQL - PRIMARY KEY 主键 MySQL - FOREIGN KEY 外键 MySQL - 复合键 MySQL - 备用键

MySQL 触发器

MySQL - 触发器 MySQL - 创建触发器 MySQL - 显示触发器 MySQL - 删除触发器 MySQL - 插入前触发器 MySQL - 插入后触发器 MySQL - 更新前触发器 MySQL - 更新后触发器 MySQL - 删除前触发器 MySQL - 删除后触发器

MySQL 8 数据类型

MySQL - 数据类型 MySQL - VARCHAR MySQL - BOOLEAN MySQL - ENUM 枚举 MySQL - DECIMAL 十进制 MySQL - INT 整数 MySQL - FLOAT 浮点数 MySQL - BIT 位 MySQL - TINYINT 微小整数 MySQL - BLOB 二进制大对象 MySQL - SET 集合

MySQL 正则表达式

MySQL - 正则表达式 MySQL - RLIKE 运算符 MySQL - NOT LIKE 运算符 MySQL - NOT REGEXP 运算符 MySQL - regexp_instr() 函数 MySQL - regexp_like() 函数 MySQL - regexp_replace() 函数 MySQL - regexp_substr() 函数

MySQL 全文搜索

MySQL - 全文搜索 MySQL - 自然语言全文搜索 MySQL - 布尔全文搜索 MySQL - 查询扩展全文搜索 MySQL - ngram 全文解析器

MySQL8 函数和运算符

MySQL - 日期和时间函数 MySQL - 算术运算符 MySQL - 数字函数 MySQL - 字符串函数 MySQL - 聚合函数

MySQL 8 其他概念

MySQL - NULL 值 MySQL - 事务 MySQL - 序列 MySQL - 处理重复项 MySQL - SQL 注入 MySQL - 子查询 MySQL - 注释 MySQL - 检查约束 MySQL - 存储引擎 MySQL - 将表导出为 CSV 文件 MySQL - 将 CSV 文件导入数据库 MySQL - UUID MySQL - 通用表表达式 MySQL - 级联删除 MySQL - Upsert 操作 MySQL - 水平分区 MySQL - 垂直分区 MySQL - 游标 MySQL - 存储函数 MySQL - SIGNAL 异常处理 MySQL - RESIGNAL 异常处理 MySQL - 字符集 MySQL - 排序规则 MySQL - 通配符 MySQL - 别名 MySQL - ROLLUP 超级聚合 MySQL - 当前日期 MySQL - 字面量 MySQL - 存储过程 MySQL - EXPLAIN 语句 MySQL - JSON MySQL - 标准差 MySQL - 查找重复记录 MySQL - 删除重复记录 MySQL - 选择随机记录 MySQL - 显示进程列表 MySQL - 更改列类型 MySQL - 重置自动增量 MySQL - Coalesce() 函数

MySQL 8 实用资源

MySQL - 实用函数 MySQL - 语句参考 MySQL - 快速指南 MySQL - 实用资源 MySQL - 讨论


MySQL - 事务

MySQL 事务

MySQL 事务是一组连续的数据库操作,其执行方式如同单个工作单元。换句话说,除非组内的每个操作都成功,否则事务永远不会完成。如果事务中的任何操作失败,整个事务都将失败。

实际上,您会将多个 SQL 查询组合成一个组,然后将它们作为事务的一部分一起执行。这将确保不会丢失数据或执行 SQL 查询失败。

事务的属性

事务有四个标准属性,通常缩写为 ACID -

  • 原子性 - 这确保事务中的所有操作都被视为一个单元。事务中的所有操作要么全部成功完成,要么全部失败。如果事务的任何部分失败,整个事务都会回滚,数据库将保持其原始状态。

  • 一致性 − 确保数据库在事务成功提交后能够正确地更改状态。

  • 隔离性 − 使事务能够独立运行且彼此透明。

  • 持久性 − 确保事务提交后,其对数据库的影响是永久性的,并且能够承受系统故障(例如断电、硬件故障)。

MySQL 中的事务语句

在 MySQL 中,事务以 START TRANSACTIONBEGINBEGIN WORK 语句开始,以 COMMITROLLBACK 语句结束。在开始和结束语句之间执行的 MySQL 命令构成了事务的主体。

要启用或禁用事务中的自动提交选项,可以使用 SET AUTOCOMMIT 命令。要启用自动提交,请将该命令设置为"1"或"ON",要禁用自动提交,请将该命令设置为"0"或"OFF"。

COMMIT 命令

COMMIT 命令是 MySQL 中的事务控制命令。发出该命令后,它将完成事务中截至该时间点对数据库表所做的更改,使这些更改成为永久性更改。因此,这些更改对 MySQL 中的其他活动会话可见。

语法

以下是在 MySQL 中执行 COMMIT 命令的语法 -

COMMIT;

示例

我们使用以下查询创建一个名为 CUSTOMERS 的表 -

CREATE TABLE CUSTOMERS (
   ID INT NOT NULL,
   NAME VARCHAR (20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY DECIMAL (18, 2),
   PRIMARY KEY (ID)
);

我们正在向上面创建的表中插入一些记录 -

INSERT INTO CUSTOMERS VALUES 
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00),
(2, 'Khilan', 25, 'Delhi', 1500.00),
(3, 'Kaushik', 23, 'Kota', 2000.00),
(4, 'Chaitali', 25, 'Mumbai', 6500.00),
(5, 'Hardik', 27, 'Bhopal', 8500.00),
(6, 'Komal', 22, 'Hyderabad', 4500.00),
(7, 'Muffy', 24, 'Indore', 10000.00);

CUSTOMERS 表显示如下 -

ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

使用以下查询启动事务并从 CUSTOMERS 表中删除 AGE 为 25 的记录,然后在数据库中提交更改 -

START TRANSACTION;
DELETE FROM CUSTOMERS WHERE AGE = 25;
COMMIT;

验证

表中的两行将被删除。为了验证,请使用以下 SELECT 语句显示修改后的 CUSTOMERS 表 -

SELECT * FROM CUSTOMERS;

以下是获得的输出 -

ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
3 Kaushik 23 Kota 2000.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00

AUTOCOMMIT 命令

您可以通过设置名为 AUTOCOMMIT 的会话变量来控制事务的行为。如果 AUTOCOMMIT 设置为 1(默认值),则每个 SQL 语句(无论是否在事务内)都将被视为一个完整的事务,并在完成后默认提交。

当 AUTOCOMMIT 设置为 0 时,通过发出 SET AUTOCOMMIT = 0 命令,后续一系列语句将像事务一样运行,在发出显式 COMMIT 语句之前不会提交任何活动。

ROLLBACK 命令

ROLLBACK 命令是一个事务命令,用于撤消事务中尚未保存(提交)到数据库的更改。此命令只能撤消自上次执行 COMMIT 或 ROLLBACK 语句以来所执行事务的效果。

语法

以下是 MySQL 中 ROLLBACK 命令的语法 -

ROLLBACK;

示例

使用以下查询,从 CUSTOMERS 表中删除 AGE 为 25 的记录,然后 ROLLBACK 数据库中的更改 -

DELETE FROM CUSTOMERS WHERE AGE = 25;
ROLLBACK;

验证

该表不会受到影响。为了验证,请使用以下 SELECT 语句显示修改后的 CUSTOMERS 表 -

SELECT * FROM CUSTOMERS;

以下是获取的表 -

ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

必须记住,ROLLBACK 仅在事务内部有效。如果您尝试在未启动事务的情况下执行该命令,则更改不会被撤销。

SAVEPOINT 命令

SAVEPOINT 是 MySQL 事务中的逻辑回滚点。

执行 ROLLBACK 命令时,它会将事务中所做的更改还原到最后一次提交,如果之前没有任何提交,则还原到事务的开始位置。但是,通过在事务中创建保存点,您可以建立特定的点,以便将事务部分回滚到这些点。您可以在事务中创建多个保存点,以便在两次提交之间拥有多个回滚选项。

语法

在事务中创建 SAVEPOINT 命令的语法如下所示 -

SAVEPOINT SAVEPOINT_NAME;

回滚到创建的 SAVEPOINT 的语法如下所示 -

ROLLBACK TO SAVEPOINT_NAME;

示例

在以下示例中,您计划从 CUSTOMERS 表中删除三条不同的记录,并在每次删除操作之前创建 SAVEPOINT。这允许您随时回滚到任何 SAVEPOINT,以将相应数据恢复到其原始状态 -

SAVEPOINT SP1;
Query OK, 0 rows affected (0.00 sec)

DELETE FROM CUSTOMERS WHERE ID=1;
Query OK, 1 row affected (0.01 sec)

SAVEPOINT SP2;
Query OK, 0 rows affected (0.00 sec)

DELETE FROM CUSTOMERS WHERE ID=2;
Query OK, 0 rows affected (0.00 sec)

SAVEPOINT SP3;
Query OK, 0 rows affected (0.00 sec)

DELETE FROM CUSTOMERS WHERE ID=3;
Query OK, 1 row affected (0.01 sec)

既然已经进行了三次删除,假设您改变主意,决定回滚到标识为 SP2 的保存点。由于 SP2 是在第一次删除之后创建的,因此此操作将撤消最后两次删除 -

ROLLBACK TO SP2;

验证

如果您使用以下 SELECT 语句显示 CUSTOMERS 表,您会注意到自回滚到 SP2 以来只发生了第一次删除 -

SELECT * FROM CUSTOMERS;

得到的结果如下所示 -

ID NAME AGE ADDRESS SALARY
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

MySQL 中的事务安全表类型

在 MySQL 中,并非所有表类型都原生支持事务。为了有效地使用事务,您应该以特定的方式创建表。虽然有各种表类型可用,但最常用的事务安全表类型是 InnoDB。

要启用 InnoDB 表支持,您可能需要在 MySQL 源代码编译期间使用特定的编译参数。如果您的 MySQL 版本不支持 InnoDB,您可以请求您的互联网服务提供商 (ISP) 提供支持 InnoDB 的 MySQL 版本,或者您可以下载并安装适用于 Windows 或 Linux/UNIX 的 MySQL-Max 二进制发行版,以便在开发环境中使用 InnoDB 表。

如果您的 MySQL 安装支持 InnoDB 表,您可以按照如下所示创建 InnoDB 表 -

CREATE TABLE tcount_tbl (
   tutorial_author varchar(40) NOT NULL,
   tutorial_count  INT
) ENGINE = InnoDB;

以下是获得的输出 -

Query OK, 0 rows affected (0.05 sec)

您也可以使用其他表类型,例如 GEMINIBDB,但这取决于您的安装环境,是否支持这两种表类型。

使用客户端程序进行事务

我们也可以使用客户端程序执行事务。

语法

要通过 PHP 程序执行事务,我们需要使用 mysqli 函数 query() 执行三个语句:"START TRANSACTION"、"COMMIT"和"ROLLBACK",如下所示 -

$sql = "START TRANSACTION";
$mysqli->query($sql);
...
$sql = "COMMIT";
$mysqli->query($sql);
...
$sql = "ROLLBACK";   
$mysqli->query($sql);
...

要通过 JavaScript 程序执行事务,我们需要使用 mysql2 库的 query() 函数执行三个语句"START TRANSACTION"、"COMMIT"和"ROLLBACK",如下所示 -

sql = "START TRANSACTION";
con.query(sql);
...
sql = "COMMIT";
con.query(sql);
...
sql = "ROLLBACK";
con.query(sql);
...

要通过 Java 程序执行事务,我们需要使用 JDBC 函数 execute() 执行三个语句"START TRANSACTION"、"COMMIT"和"ROLLBACK",如下所示 -

String sql = "START TRANSACTION";
statement.execute(sql);
...
String sql = "COMMIT";
statement.execute(sql);
...
String sql = "ROLLBACK";
statement.execute(sql);
...

要通过 Python 程序执行事务,我们需要使用 MySQL Connector/Pythonexecute() 函数执行三个语句"START TRANSACTION"、"COMMIT"和"ROLLBACK",如下所示:−

connection.start_transaction()
...
connection.commit()
...
connection.rollback()
...

示例

以下是程序−

 $dbhost = 'localhost';
 $dbuser = 'root';
 $dbpass = 'password';
 $db = 'TUTORIALS';
 $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
 if ($mysqli->connect_errno) {
     printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf('Connected successfully.
'); //start transaction $sql = "START TRANSACTION"; if($mysqli->query($sql)){ printf("Transaction started....! "); } //print table record $sql = "SELECT * FROM CUSTOMERS"; if($result = $mysqli->query($sql)){ printf("Table records after transaction...! "); while($row = mysqli_fetch_array($result)){ printf("ID %d, NAME %s, AGE %d, ADDRESS %s, SALARY %f", $row['ID'], $row['NAME'], $row['AGE'], $row['ADDRESS'], $row['SALARY']); printf(" "); } } //let's delete some records $sql = "DELETE FROM CUSTOMERS WHERE AGE = 25"; if($mysqli->query($sql)){ printf("Records with age = 25 are deleted successfully....! "); } //lets delete some more records.. $sql = "DELETE FROM CUSTOMERS WHERE SALARY = 2000"; if($mysqli->query($sql)){ printf("Records with salary = 2000 are deleted successfully....! "); } printf("Table data after second delete (before rollback)...! "); $sql = "SELECT * FROM CUSTOMERS"; if($result = $mysqli->query($sql)){ while($row = mysqli_fetch_array($result)){ printf("ID %d, NAME %s, AGE %d, ADDRESS %s, SALARY %f", $row['ID'], $row['NAME'], $row['AGE'], $row['ADDRESS'], $row['SALARY']); printf(" "); } } $sql = "ROLLBACK"; if($mysqli->query($sql)){ printf("Transaction rollbacked successfully..! "); } printf("Table data after rollback: "); $sql = "SELECT * FROM CUSTOMERS"; if($result = $mysqli->query($sql)){ while($row = mysqli_fetch_array($result)){ printf("ID %d, NAME %s, AGE %d, ADDRESS %s, SALARY %f", $row['ID'], $row['NAME'], $row['AGE'], $row['ADDRESS'], $row['SALARY']); printf(" "); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();

输出

获得的输出如下所示 -

Transaction started....!
Table records after transaction...!
ID 1, NAME Ramesh, AGE 32, ADDRESS Ahmedabad, SALARY 2000.000000
ID 2, NAME Khilan, AGE 25, ADDRESS Delhi, SALARY 1500.000000
ID 3, NAME kaushik, AGE 23, ADDRESS Kota, SALARY 2000.000000
ID 4, NAME Chaitali, AGE 25, ADDRESS Mumbai, SALARY 6500.000000
ID 5, NAME Hardik, AGE 27, ADDRESS Bhopal, SALARY 8500.000000
ID 6, NAME Komal, AGE 22, ADDRESS MP, SALARY 4500.000000
ID 7, NAME Muffy, AGE 24, ADDRESS Indore, SALARY 10000.000000
Records with age = 25 are deleted successfully....!
Records with salary = 2000 are deleted successfully....!
Table data after second delete (before rollback)...!
ID 5, NAME Hardik, AGE 27, ADDRESS Bhopal, SALARY 8500.000000
ID 6, NAME Komal, AGE 22, ADDRESS MP, SALARY 4500.000000
ID 7, NAME Muffy, AGE 24, ADDRESS Indore, SALARY 10000.000000
Transaction rollbacked successfully..!
Table data after rollback:
ID 1, NAME Ramesh, AGE 32, ADDRESS Ahmedabad, SALARY 2000.000000
ID 2, NAME Khilan, AGE 25, ADDRESS Delhi, SALARY 1500.000000
ID 3, NAME kaushik, AGE 23, ADDRESS Kota, SALARY 2000.000000
ID 4, NAME Chaitali, AGE 25, ADDRESS Mumbai, SALARY 6500.000000
ID 5, NAME Hardik, AGE 27, ADDRESS Bhopal, SALARY 8500.000000
ID 6, NAME Komal, AGE 22, ADDRESS MP, SALARY 4500.000000
ID 7, NAME Muffy, AGE 24, ADDRESS Indore, SALARY 10000.000000   
var mysql = require('mysql2');
var con = mysql.createConnection({
host:"localhost",
user:"root",
password:"password"
});
//连接到 MySQL
 con.connect(function(err) {
 if (err) throw err;
//   console.log("Connected successfully...!");
//   console.log("--------------------------");
 sql = "USE TUTORIALS";
 con.query(sql);
 sql = "START TRANSACTION";
con.query(sql, function(err, result){
    if (err) throw err;
    console.log("Transaction started....!");
});
 sql = "SELECT * FROM CUSTOMERS";
 con.query(sql, function(err, result){
    console.log("Table records after transaction...!");
    if (err) throw err;
    console.log(result);
    });
//delete record
sql = "DELETE FROM CUSTOMERS WHERE AGE  = 25";
con.query(sql, function(err, result){
    if (err) throw err;
    console.log("Records with age = 25 are deleted successfully....!");
});
//now lets delete more records
sql = "DELETE FROM CUSTOMERS WHERE SALARY  = 2000";
con.query(sql, function(err, result){
    if (err) throw err;
    console.log("Records with salary = 2000 are deleted successfully....!");
});
//print table records before rollback;
sql = "SELECT * FROM CUSTOMERS";
con.query(sql, function(err, result){
   console.log("Table Data After Second Delete (Before Rollback)");
   if (err) throw err;
   console.log(result);
   });
//rollback the transaction
sql = "ROLLBACK";
con.query(sql, function(err, result){
    if (err) throw err;
    console.log("Transaction rollbacked successfully..!");
});
//print table data after rollback;
sql = "SELECT * FROM CUSTOMERS";
 con.query(sql, function(err, result){
    console.log("Table records after rollback...!");
    if (err) throw err;
    console.log(result);
    });
});   

输出

获得的输出如下所示 -

Transaction started....!
Table records after transaction...!
[
  {
    ID: 1,
    NAME: 'Ramesh',
    AGE: 32,
    ADDRESS: 'Ahmedabad',
    SALARY: '2000.00'
  },
  {
    ID: 2,
    NAME: 'Khilan',
    AGE: 25,
    ADDRESS: 'Delhi',
    SALARY: '1500.00'
  },
  {
    ID: 3,
    NAME: 'kaushik',
    AGE: 23,
    ADDRESS: 'Kota',
    SALARY: '2000.00'
  },
  {
    ID: 4,
    NAME: 'Chaitali',
    AGE: 25,
    ADDRESS: 'Mumbai',
    SALARY: '6500.00'
  },
  {
    ID: 5,
    NAME: 'Hardik',
    AGE: 27,
    ADDRESS: 'Bhopal',
    SALARY: '8500.00'
  },
  { ID: 6, NAME: 'Komal', AGE: 22, ADDRESS: 'MP', SALARY: '4500.00' },
  {
    ID: 7,
    NAME: 'Muffy',
    AGE: 24,
    ADDRESS: 'Indore',
    SALARY: '10000.00'
  }
]
Records with age = 25 are deleted successfully....!
Records with salary = 2000 are deleted successfully....!
Table Data After Second Delete (Before Rollback)
[
  {
    ID: 5,
    NAME: 'Hardik',
    AGE: 27,
    ADDRESS: 'Bhopal',
    SALARY: '8500.00'
  },
  { ID: 6, NAME: 'Komal', AGE: 22, ADDRESS: 'MP', SALARY: '4500.00' },
  {
    ID: 7,
    NAME: 'Muffy',
    AGE: 24,
    ADDRESS: 'Indore',
    SALARY: '10000.00'
  }
]
Transaction rollbacked successfully..!
Table records after rollback...!
[
  {
    ID: 1,
    NAME: 'Ramesh',
    AGE: 32,
    ADDRESS: 'Ahmedabad',
    SALARY: '2000.00'
  },
  {
    ID: 2,
    NAME: 'Khilan',
    AGE: 25,
    ADDRESS: 'Delhi',
    SALARY: '1500.00'
  },
  {
    ID: 3,
    NAME: 'kaushik',
    AGE: 23,
    ADDRESS: 'Kota',
    SALARY: '2000.00'
  },
  {
    ID: 4,
    NAME: 'Chaitali',
    AGE: 25,
    ADDRESS: 'Mumbai',
    SALARY: '6500.00'
  },
  {
    ID: 5,
    NAME: 'Hardik',
    AGE: 27,
    ADDRESS: 'Bhopal',
    SALARY: '8500.00'
  },
  { ID: 6, NAME: 'Komal', AGE: 22, ADDRESS: 'MP', SALARY: '4500.00' },
  {
    ID: 7,
    NAME: 'Muffy',
    AGE: 24,
    ADDRESS: 'Indore',
    SALARY: '10000.00'
  }
]   
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Transaction {
   public static void main(String[] args) {
      String url = "jdbc:mysql://localhost:3306/TUTORIALS";
      String user = "root";
      String password = "password";
      ResultSet rs;
      try {
         Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, password);
            Statement st = con.createStatement();
            //System.out.println("Database connected successfully...!");
            //开始事务
            String sql = "START TRANSACTION";
            st.execute(sql);
            System.out.println("Transaction started....!");
            //交易开始后打印客户记录
            String sql1 = "SELECT * FROM CUSTOMERS";
            rs = st.executeQuery(sql1);
            System.out.println("Table records after starting transaction: ");
            while(rs.next()) {
               String id = rs.getString("id");
               String name = rs.getString("name");
               String age = rs.getString("age");
               String address = rs.getString("address");
               String salary = rs.getString("salary");
               System.out.println("Id: " + id + ", Name: " + name +   ", Age: " + age +   ", Address: " + address +  ", Salary: " + salary);
            }
            //删除一些记录
            String sql2 = "DELETE FROM CUSTOMERS WHERE AGE = 25";
            st.execute(sql2);
            System.out.println("Customer with age 25 deleted successfully...!");
            String sql4 = "DELETE FROM CUSTOMERS WHERE SALARY  = 2000";
            st.execute(sql4);
            System.out.println("Customer with age 2000 deleted successfully...!");
            String sql5 = "SELECT * FROM CUSTOMERS";
            rs = st.executeQuery(sql5);
            System.out.println("Table records before rollback: ");
            while(rs.next()) {
               String id = rs.getString("id");
               String name = rs.getString("name");
               String age = rs.getString("age");
               String address = rs.getString("address");
               String salary = rs.getString("salary");
               System.out.println("Id: " + id + ", Name: " + name +   ", Age: " + age +   ", Address: " + address +  ", Salary: " + salary);
            }
            //回滚事务
            String r = "ROLLBACK";
            st.execute(r);
            System.out.println("Transaction rollbacked successfully...!");
            String sql6 = "SELECT * FROM CUSTOMERS";
            rs = st.executeQuery(sql6);
            System.out.println("Table records after rollback: ");
            while(rs.next()) {
               String id = rs.getString("id");
               String name = rs.getString("name");
               String age = rs.getString("age");
               String address = rs.getString("address");
               String salary = rs.getString("salary");
               System.out.println("Id: " + id + ", Name: " + name +   ", Age: " + age +   ", Address: " + address +  ", Salary: " + salary);
            }
      }catch(Exception e) {
         e.printStackTrace();
      }
   }
}   

输出

获得的输出如下所示 -

Transaction started....!
Table records after starting transaction: 
Id: 1, Name: Ramesh, Age: 32, Address: Ahmedabad, Salary: 2000.00
Id: 2, Name: Khilan, Age: 25, Address: Delhi, Salary: 1500.00
Id: 3, Name: kaushik, Age: 23, Address: Kota, Salary: 2000.00
Id: 4, Name: Chaitali, Age: 25, Address: Mumbai, Salary: 6500.00
Id: 5, Name: Hardik, Age: 27, Address: Bhopal, Salary: 8500.00
Id: 6, Name: Komal, Age: 22, Address: MP, Salary: 4500.00
Id: 7, Name: Muffy, Age: 24, Address: Indore, Salary: 10000.00
Customer with age 25 deleted successfully...!
Customer with age 2000 deleted successfully...!
Table records before rollback: 
Id: 5, Name: Hardik, Age: 27, Address: Bhopal, Salary: 8500.00
Id: 6, Name: Komal, Age: 22, Address: MP, Salary: 4500.00
Id: 7, Name: Muffy, Age: 24, Address: Indore, Salary: 10000.00
Transaction rollbacked successfully...!
Table records after rollback: 
Id: 1, Name: Ramesh, Age: 32, Address: Ahmedabad, Salary: 2000.00
Id: 2, Name: Khilan, Age: 25, Address: Delhi, Salary: 1500.00
Id: 3, Name: kaushik, Age: 23, Address: Kota, Salary: 2000.00
Id: 4, Name: Chaitali, Age: 25, Address: Mumbai, Salary: 6500.00
Id: 5, Name: Hardik, Age: 27, Address: Bhopal, Salary: 8500.00
Id: 6, Name: Komal, Age: 22, Address: MP, Salary: 4500.00
Id: 7, Name: Muffy, Age: 24, Address: Indore, Salary: 10000.00
import mysql.connector
# 建立连接
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
# 创建游标对象
cursorObj = connection.cursor()
# 启动事务
connection.start_transaction()
# 删除前显示表
select_query = "SELECT * FROM customers"
cursorObj.execute(select_query)
print("Table Data after starting Transaction:")
for row in cursorObj.fetchall():
    print(row)
# 执行 DELETE 语句
delete_query = "DELETE FROM customer WHERE AGE = 25"
cursorObj.execute(delete_query)
print("Rows with AGE = 25 are deleted.")
# 提交事务
connection.commit()
print("Transaction committed successfully.")
# 删除后显示表格(更改是永久性的)
cursorObj.execute(select_query)
print("Table Data After Transaction:")
for row in cursorObj.fetchall():
    print(row)
# 现在,让我们删除更多记录
delete_query1 = "DELETE FROM customer WHERE SALARY = 2000"
cursorObj.execute(delete_query1)
print("Rows with SALARY = 2000 are deleted.")
# 显示第二次删除操作后的表(更改尚未提交)
cursorObj.execute(select_query)
print("Table Data After Second Delete (Before Rollback):")
for row in cursorObj.fetchall():
    print(row)
# 回滚事务
connection.rollback()
print("Transaction rollbacked successfully.")
# 显示回滚后的表格(更改被恢复)
cursorObj.execute(select_query)
print("Table Data After Rollback:")
for row in cursorObj.fetchall():
    print(row)
# 关闭游标和连接
cursorObj.close()
connection.close() 

输出

获得的输出如下所示 -

Table Data after starting Transaction:
(1, 'Ramesh', 32, 'Ahmedabad', Decimal('2000.00'))
(2, 'Khilan', 25, 'Delhi', Decimal('1500.00'))
(3, 'kaushik', 23, 'Kota', Decimal('2000.00'))
(4, 'Chaitali', 25, 'Mumbai', Decimal('6500.00'))
(5, 'Hardik', 27, 'Bhopal', Decimal('8500.00'))
(6, 'Komal', 22, 'MP', Decimal('4500.00'))
(7, 'Muffy', 24, 'Indore', Decimal('10000.00'))
Rows with AGE = 25 are deleted.
Transaction committed successfully.
Table Data After Transaction:
(1, 'Ramesh', 32, 'Ahmedabad', Decimal('2000.00'))
(3, 'kaushik', 23, 'Kota', Decimal('2000.00'))
(5, 'Hardik', 27, 'Bhopal', Decimal('8500.00'))
(6, 'Komal', 22, 'MP', Decimal('4500.00'))
(7, 'Muffy', 24, 'Indore', Decimal('10000.00'))
Rows with SALARY = 2000 are deleted.
Table Data After Second Delete (Before Rollback):
(5, 'Hardik', 27, 'Bhopal', Decimal('8500.00'))
(6, 'Komal', 22, 'MP', Decimal('4500.00'))
(7, 'Muffy', 24, 'Indore', Decimal('10000.00'))
Transaction rollbacked successfully.
Table Data After Rollback:
(1, 'Ramesh', 32, 'Ahmedabad', Decimal('2000.00'))
(3, 'kaushik', 23, 'Kota', Decimal('2000.00'))
(5, 'Hardik', 27, 'Bhopal', Decimal('8500.00'))
(6, 'Komal', 22, 'MP', Decimal('4500.00'))
(7, 'Muffy', 24, 'Indore', Decimal('10000.00'))