Skapa en Utility-klass för anslutningshantering för att hantera den på en enda punkt i hela programmet.
Läs inte in DataSource
varje gång du behöver en ny anslutning.
Exempelkod:
public class ConnectionUtil {
private DataSource dataSource;
private static ConnectionUtil instance = new ConnectionUtil();
private ConnectionUtil() {
try {
Context initContext = new InitialContext();
dataSource = (DataSource) initContext.lookup("JNDI_LOOKUP_NAME");
} catch (NamingException e) {
e.printStackTrace();
}
}
public static ConnectionUtil getInstance() {
return instance;
}
public Connection getConnection() throws SQLException {
Connection connection = dataSource.getConnection();
return connection;
}
public void close(Connection connection) throws SQLException {
if (connection != null && !connection.isClosed()) {
connection.close();
}
connection = null;
}
}
Stäng alltid anslutningen och hantera den i try-catch-finally
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = ConnectionUtil.getInstance().getConnection();
...
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
ConnectionUtil.getInstance().close(conn);
}
}