关闭数据库连接与自动提交

关闭数据库连接与自动提交

 // 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 关闭数据库连接与自动提交--https://blog.csdn.net/hjiacheng/article/details/53193361

05-04 12:23