try { Connection conn = DriverManager.getConnection(url, user, password); // Do some database operations if (!conn.isClosed()) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); }
try { Connection conn = dataSource.getConnection(); // Do some database operations } catch (SQLException e) { e.printStackTrace(); } finally { if (!conn.isClosed()) { conn.close(); } }In this example, we obtain a connection from a DataSource object using dataSource.getConnection() method. Then we perform some database operations and close the connection using conn.close() method inside a finally block. We also check if the connection is still open using isClosed() method before closing it. The java.sql.Connection interface is part of the JDBC API, which is included in the Java SE (Standard Edition) platform.