我正在尝试在Java中为我的Web应用程序使用池连接。我使用的是Oracle数据库,这里是我的代码:我是否正确地关闭了此Oracle池连接?
public class DatabaseHandler
{
static private Connection m_database = null;
static private OracleConnectionPoolDataSource pooledSource = null;
/**
* Attempts to open an Oracle database located at the specified serverName and port.
* @param serverName Address of the server.
* @param portNumber Port to connect to.
* @param sid SID of the server.
* @param userName Username to login with.
* @param password Password to login with.
* @throws WebApplicationException with response code 500 Internal Server Error.
*/
static public void openDatabase(String userName, String password,String serverName,int portNumber, String sid)
throws WebApplicationException
{
try
{
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
// Create a connection to the database
String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
pooledSource = new OracleConnectionPoolDataSource();
pooledSource.setUser(userName);
pooledSource.setURL(url);
pooledSource.setPassword(password);
m_database = pooledSource.getConnection();
}
catch (ClassNotFoundException e)
{
// Could not find the database driver
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
catch (SQLException e)
{
// Could not connect to the database
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
/**
* Attempts to execute the specified SQL query.
* @throws WebApplicationException with a response code of Bad Request
* if the query is invalid SQL.
*/
static public ResultSet makeQuery(String query) throws WebApplicationException
{
ResultSet rs = null;
if (m_database != null)
{
try
{
Statement stmt = m_database.createStatement();
rs = stmt.executeQuery(query);
}
catch (SQLException e)
{
// invalid query
System.out.println(query);
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
return rs;
}
/**
* Attempts to close the database.
* @throws WebApplicationException with a response code of 500 Server error
*/
static public void closeDatbase() throws WebApplicationException
{
try
{
m_database.close();
pooledSource.close();
}
catch(SQLException e)
{
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
}
我在Eclipse这样做的,我有一个警告,pooledSource.close()
已被弃用。我从来没有使用过连接池,我只是想确保我做的一切都正确。有没有更好的方法来关闭Oracle池化资源?
因此,我不需要显式关闭池连接,它是为我处理的?我想这可能是这种情况,但我想100%肯定,所以我不放弃连接而不是关闭连接。 – 2011-06-08 14:48:40
您不需要关闭连接池。如果从池中获得连接,则“连接”属于连接池,因此关闭连接会将其自动返回到池中。 – 2011-06-08 14:50:38
谢谢你的详细解释。 – 2011-06-08 14:52:19