JDBC and Connection Pools
JDBC provides a standard API for relational database access. A connection pool reuses database connections rather than creating a new connection for every request.
try (Connection connection = dataSource.getConnection();
PreparedStatement statement =
connection.prepareStatement(
"select id, name from users where id = ?")) {
statement.setString(1, userId);
try (ResultSet rs = statement.executeQuery()) {
if (rs.next()) {
return rs.getString("name");
}
}
}
Always use parameterized queries. Pool size should account for database capacity and query latency; making it huge can overload the database.
SQL injection
Never concatenate untrusted input into SQL. Use prepared statements or a safe data-access abstraction.
Key Takeaways
- Use prepared statements for values.
- Connection pools are shared scarce resources.
- Database pool sizing must account for database capacity.