import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class CloseConnectionDemo { public static void main(String[] args) { String url = "jdbc:mysql://localhost/mydatabase"; String user = "root"; String password = "password"; try (Connection conn = DriverManager.getConnection(url, user, password)) { // Use the connection } catch (SQLException ex) { ex.printStackTrace(); } } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class CloseConnectionDemo { public static void main(String[] args) { String url = "jdbc:mysql://localhost/mydatabase"; String user = "root"; String password = "password"; Connection conn = null; try { conn = DriverManager.getConnection(url, user, password); // Use the connection } catch (SQLException ex) { ex.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException ex) { ex.printStackTrace(); } } } }In this example, we create a `Connection` object using the `DriverManager.getConnection()` method and close it explicitly in the `finally` block using the `close()` method. Both examples use the `java.sql.Connection` interface which is part of the JDBC (Java Database Connectivity) API.