12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
-
- public class TestTransaction {
-
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- 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();
- // JAVA默认为TRUE,我们自己处理需要设置为FALSE,并且修改为手动提交,才可以调用rollback()函数
- con.setAutoCommit(false);
- stmt.addBatch("insert into people values(078,'ding','duo')");
- stmt.addBatch("insert into people values(30,'nokia','ddd')");
- stmt.executeBatch();
- // 事务提交
- con.commit();
- // 设置为自动提交,改为TRUE
- con.setAutoCommit(true);
-
- /*
- * String sql = "select * from people"; rs = stmt.executeQuery(sql);
- * while(rs.next()){ System.out.println(rs.getString("id") + " " +
- * rs.getString("name")); }
- */
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException se) {
- se.printStackTrace();
- try {
- // 产生的任何SQL异常都需要进行回滚,并设置为系统默认的提交方式,即为TRUE
- if (con != null) {
- con.rollback();
- 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();
- }
- }
- }
-
- }
|