事务:操作序列要么都执行要么都不执行,可以看作一组SQL语句
四个特征:
1.原子性:要么全部成功,要么全部失败
2.一致性:是指事务开始之前和结束以后,数据库的完整性约束没有被破坏
3.隔离性:对数据库进行修改的多个事务是彼此隔离的
4.持久性:事务完成之后对系统的影响是永久的
事务的语句:
1.开始事务 BEGIN TRANSACTION
2.提交事务 COMMIT TRANSACTION
3.回滚事务 ROLLBACK TRANSACTION
新建TransactionTest.java
command+shift+f格式化代码
insertUserData();
insertAddressData();选中右键Surround With-Try/catch Block
TransactionTest.java文件内容如下:
package com.jikexueyuan.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TransactionTest {
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");// 注册驱动程序;Class为封装:jvm中类的信息
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "");// 获取数据库的连接:url
// 用户名
// 密码
// jsp_db为数据库软件中创建的数据库
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void insertUserData(Connection conn) throws SQLException {
String sql = "INSERT INTO tbl_user(id,name,password,email)" + "VALUES(10,'Tom','123456','tom@gmail.com')";
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向用户表插入了" + count + " 条记录");
}
public static void insertAddressData(Connection conn) throws SQLException {
String sql = "INSERT INTO tbl_address(id,city,country,user_id)" + "VALUES(1,'shanghai','china','10')";
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向地址表插入了" + count + " 条记录");
}
public static void main(String[] args) {
Connection conn = null;
//选中右键Surround With-Try/catch Block
try {
conn = getConnection();
conn.setAutoCommit(false);//禁止事务自动提交
insertUserData(conn);
insertAddressData(conn);
conn.commit();
} catch (SQLException e) {
System.out.println("========捕获到SQL异常=======");
e.printStackTrace();
try {
conn.rollback();//回滚事务
System.out.println("========事务回滚成功==========");
} catch (Exception e2) {
e2.printStackTrace();
}
}finally{
try {
if(conn!= null){
conn.close();
}
} catch (Exception e3) {
e3.printStackTrace();
}
}
}
}