我正尝试关闭DriverManagerDataSource
的连接,如下所示:
public final class DbConnect {
private static final Logger LOG = Logger.getLogger(DbConnect.class);
public static DriverManagerDataSource getDataSource(String dbHost, int dbPort, String dbUser, String dbPassword, String dbSID)
{
LOG.info("getDataSource");
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("oracle.jdbc.OracleDriver");
ds.setUrl(String.format("jdbc:oracle:thin:@%s:%d:%s", dbHost, dbPort, dbSID));
LOG.info("url: " + ds.getUrl());
ds.setUsername(dbUser);
ds.setPassword(dbPassword);
try {
ds.getConnection().setAutoCommit(true);
} catch (SQLException e) {
LOG.info("Could not set db connecion to autocommit", e);
}
return ds;
}
/**
* Test connection to Database
* @param dbHost Database host name or IP
* @param dbPort Database port number
* @param dbUser Database user name
* @param dbPassword Database password
* @param dbSID Database service ID
* @return true if connection successful or throws CmException in case of failure
*/
public static boolean testConnection(String dbHost, int dbPort, String dbUser, String dbPassword, String dbSID) throws CmException
{
DriverManagerDataSource ds = getDataSource(dbHost, dbPort, dbUser, dbPassword, dbSID);
JdbcTemplate select = new JdbcTemplate(ds);
try {
select.queryForInt("SELECT 1 from DUAL");
} catch (Throwable ex){
LOG.info("Could not connect to DB: " + ex.getMessage(), ex);
throw new CmException(ex.getMessage());
} finally {
closeDBConnection(ds);
}
return true;
}
public static void closeDBConnection(DriverManagerDataSource ds)
{
LOG.debug("Close the DB connection");
if(ds == null) { return; }
try {
LOG.debug("Getting the connection from data source");
Connection conn = ds.getConnection();
if(conn != null) {
LOG.debug("Try closing the connection");
conn.close();
}
} catch (Exception ex) {
LOG.error("Could not close connection to DB: " + ex.getMessage(), ex);
}
}
} }
但是请注意,该连接没有关闭,我所做的是关闭打开的连接的正确方法吗?如果没有,该如何改善我的代码?