import java.sql.*;
public class RollBack {
/**
* 数据库的属性信息
*/
/**
* 数据库主机 IP地址
*/
static final String IP = "127.0.0.1";
/**
* 数据库端口号
*/
static final String PORT = "1521";
/**
* 数据库名
*/
static final String DB_NAME = "yztc";
/**
* 数据库 URL
*/
static final String URL = "jdbc:oracle:thin:@" + IP + ":" + PORT + ":" + DB_NAME;
/**
* 数据库连接用户名
*/
static final String USER = "scott";
/**
* 用户密码
*/
static final String PSW = "tiger";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;
PreparedStatement ps3 = null;
try {
conn = DriverManager.getConnection(URL, USER, PSW);
// 开启事务(手动提交事务)
conn.setAutoCommit(false);
// 插入语句
String sql = "INSERT INTO person(name,psw,age,sex,description) VALUES(?,?,?,?,?)";
ps1 = conn.prepareStatement(sql);
ps1.setString(1, "李四");
ps1.setString(2, "123");
ps1.setInt(3, 18);
ps1.setString(4, "男");
ps1.setString(5, "个人说明");
ps1.executeUpdate();
// 设置回滚点
Savepoint setSavepoint = conn.setSavepoint();
// 更新数据
String sql2 = "UPDATE person SET name=? WHERE personid=?";
ps2 = conn.prepareStatement(sql2);
ps2.setString(1, "张三");
ps2.setInt(2, 70);
ps2.executeUpdate();
// 删除数据
String sql3 = "DELETE FROM person WHERE personid=?";
ps3 = conn.prepareStatement(sql3);
ps3.setInt(1, 70);
ps3.executeUpdate();
// 回滚到设置回滚点的位置
conn.rollback(setSavepoint);
// 提交事务
conn.commit();
// 恢复最初的设置
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (ps1 != null) {
try {
ps1.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps2 != null) {
try {
ps2.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps3 != null) {
try {
ps3.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
jdbc连接数据库数据回滚
最新推荐文章于 2023-04-08 08:18:16 发布