標籤:final val 關閉自動 pwd mit out false bsp nal
// Jdbc關閉資料庫連接時,會隱含一個提交事務的操作 private final static String DB_DRIVER = "oracle.jdbc.driver.OracleDriver"; private final static String DB_CONNECTION = "jdbc:oracle:thin:@127.0.0.1:1521:mydb01"; private final static String DB_NAME = "scott"; private final static String DB_PWd = "scott"; //jdbc關閉自動認可. 在對資料庫的操作未提交時,當conn.close()時,會預設先提交事務,再關閉串連. public static void test1() { Connection conn = null; CallableStatement callStmt = null; PreparedStatement ps = null; try { Class.forName(DB_DRIVER); conn = DriverManager.getConnection(DB_CONNECTION, DB_NAME, DB_PWd); conn.setAutoCommit(false); //關閉自動認可 ps = conn.prepareStatement("insert into t_user values (?, ?, ?)"); ps.setString(1, "1"); ps.setString(2, "1"); ps.setString(3, "1"); int results = ps.executeUpdate(); //conn.commit();//不手動提交 System.out.println("插入了" + results + "條: "); } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(System.out); } finally { try { conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (null != callStmt) { try { callStmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (null != conn) { try { conn.close();// jdbc關閉自動認可. 在jdbc未提交時,當conn.close()時,會預設先提交事務,再關閉串連. } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //jdbc預設自動認可. 在對資料庫的操作未手動提交時,也會立即提交到資料庫並生效 public static void test2() { Connection conn = null; CallableStatement callStmt = null; PreparedStatement ps = null; try { Class.forName(DB_DRIVER); conn = DriverManager.getConnection(DB_CONNECTION, DB_NAME, DB_PWd); // conn.setAutoCommit(false); //jdbc預設自動認可 ps = conn.prepareStatement("insert into t_user values (?, ?, ?)"); ps.setString(1, "1"); ps.setString(2, "1"); ps.setString(3, "1"); int results = ps.executeUpdate(); //注意,這一步操作就被提交到資料庫了!!! //conn.commit();//不手動提交 System.out.println("插入了" + results + "條: "); } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(System.out); } finally { try { conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (null != callStmt) { try { callStmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (null != conn) { try { conn.close();// jdbc關閉串連 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
完全引用自
JDBC 關閉資料庫連接與自動認可--53193361
JDBC 關閉資料庫連接與自動認可【轉】