请问下面的代码是否可以正确使用连接池(DBCP)?
我提供 BasicDataSource 的实用程序类如下(几乎与 apache 示例相同)
public class DatabaseUtility {
private static BasicDataSource dataSource;
public static BasicDataSource getDataSource(Properties prop) {
if (dataSource == null)
{
BasicDataSource ds = new BasicDataSource();
ds.setUrl("jdbc:oracle:thin:@"+ prop.getProperty("db") + ":" + prop.getProperty("dbPort") + "/" +
prop.getProperty("dbService"));
ds.setUsername(prop.getProperty("dbUser"));
ds.setPassword(prop.getProperty("dbPassword"));
ds.setMinIdle(5);
ds.setMaxIdle(10);
ds.setMaxOpenPreparedStatements(100);
dataSource = ds;
}
return dataSource;
}
然后我将上述内容用作:
public class MyClass {
public static boolean isNew(Properties prop, String label) {
Connection connection = null;
PreparedStatement ps = null;
try {
BasicDataSource dataSource = DatabaseUtility.getDataSource(prop);
connection = dataSource.getConnection();
ps = connection.prepareStatement("Select * from my_table where LABEL = CAST( ? AS CHAR(35))");
ps.setString(1, label);
if (ps.executeQuery().isBeforeFirst()) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ps != null)
ps.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
System.out.println("Error while closing resource :");
e.printStackTrace();
}
}
return true;
}
}
MyClass 类可能被多个衍生线程使用。我没有看到此代码的任何潜在问题?
非常感谢