Quick Answer
Connect to databases using JDBC.
Understanding the Issue
JDBC provides standard API for database access. Modern best practices include try-with-resources and connection pooling.
The Problem
This code demonstrates the issue:
Java
Error
// Need to query a database
The Solution
Here's the corrected code:
Java
Fixed
// Basic connection
try (Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users")) {
while (rs.next()) {
System.out.println(rs.getString("username"));
}
}
// Using connection pool (e.g., HikariCP)
HikariConfig config = new HikariConfig();
config.setJdbcUrl(url);
try (HikariDataSource ds = new HikariDataSource(config)) {
// Get connections from pool
}
Key Takeaways
Always use connection pooling in production.