JDBC中处理事务(SXT)
Demo
- import java.sql.*;
- public class TestTransaction
- {
- /**
- * @JDBC中处理事务
- */
- public static void main(String[] args)
- {
- // 1.不用PreparedStatement
- Connection conn = null;
- Statement stmt = null;
- String url = "jdbc:mysql://localhost:3306/college";
- String user = "root";
- String password = "123456";
- try
- {
- Class.forName("com.mysql.jdbc.Driver");
- conn = DriverManager.getConnection(url, user, password);
- conn.setAutoCommit(false);
- stmt = conn.createStatement();
- stmt.addBatch("insert into user values(301,'go1','123','0')");
- stmt.addBatch("insert into user values(302,'go2','1234','00')");
- stmt.addBatch("insert into user values(303,'go3','12345','000')");
- stmt.executeBatch();
- conn.commit();
- conn.setAutoCommit(true);
- } catch (ClassNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (SQLException e)
- {
- e.printStackTrace();
- try
- {
- if (conn != null)
- {
- conn.rollback();
- conn.setAutoCommit(true);
- }
- } catch (SQLException e1)
- {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- } finally
- {
- try
- {
- if (stmt != null)
- {
- stmt.close();
- stmt = null;
- }
- if (conn != null)
- {
- conn.close();
- conn = null;
- }
- } catch (SQLException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }