import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* java 事务回滚操作
*
**/
public class TestTransaction {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "root");
System.out.println("数据库已连接!");
stmt = con.createStatement();
修改默认的自动提交数据,执行多条数据
con.setAutoCommit(false);
stmt.addBatch(sql);
stmt.addBatch(sql1);
stmt.executeBatch();// 提交事务
con.commit();
con.setAutoCommit(true);// 恢复默认 } catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException se) {
se.printStackTrace();
try {
if (con != null) {
con.rollback();//出现sql异常,事务回滚
con.setAutoCommit(true);//设置提交方式为默认方式 }
} catch (SQLException se1) {
se.printStackTrace();
}
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* java 事务回滚操作
*
**/
public class TestTransaction {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "root");
System.out.println("数据库已连接!");
stmt = con.createStatement();
修改默认的自动提交数据,执行多条数据
con.setAutoCommit(false);
stmt.addBatch(sql);
stmt.addBatch(sql1);
stmt.executeBatch();// 提交事务
con.commit();
con.setAutoCommit(true);// 恢复默认 } catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException se) {
se.printStackTrace();
try {
if (con != null) {
con.rollback();//出现sql异常,事务回滚
con.setAutoCommit(true);//设置提交方式为默认方式 }
} catch (SQLException se1) {
se.printStackTrace();
}
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}