在我们刚开始学习 JDBC时,由于没有使用数据库连接池,我们代码中的每一次连接都需要我们自己来关闭。
不过很多人,都没有正确关闭,包括一些 JDBC的教程。
例如: https://www.javatpoint.com/example-to-connect-to-the-oracle-database
没有正确关闭:
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
正确关闭:
import java.sql.*;
class OracleCon{
public static void main(String args[]){
ResultSet rs = null;
Connection con = null;
Statement stmt = null;
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
stmt=con.createStatement();
//step4 execute query
rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close(); //如果上面代码抛出异常是执行不到这里的
}catch(Exception e){ System.out.println(e);}
}finally{
try {
if(rs !=null)rs.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
try {
if(stmt !=null)stmt.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
try {
if(con !=null)con.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}
这样看起来,不美观,并且我们如果代码 有 查询,插入,删除,更新,为了够复用我们封装一下。这样我们只需要在 finally 里调用 close方法就可以了。
/**
* 关闭数据连接
* @param con
* @param sta
* @param rs //针对查询
*/
private void close(Connection con,Statement sta,ResultSet rs){
try {
if(rs !=null)rs.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
try {
if(sta !=null)sta.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
try {
if(con !=null)con.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
/**
* 关闭数据连接
* @param con
* @param sta
* @param rs
*/
private void close(Connection con,Statement sta,ResultSet rs){
try {
if(rs !=null)rs.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
try {
if(sta !=null)sta.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
try {
if(con !=null)con.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
我们编程的时候,很多时候由于一些原因,写的代码总是有些问题,为了避免一个很常见的问题,建议使用
sonarLint 对代码进行扫描,根据sonar提示的进行修改 。
我开始也没有意识到,我没有正确关闭连接,sonarLint提示了我,之后进行修改。