Java JDBC Guide
· By Saurabh Editorial · Java
Work with relational databases from Java using JDBC — connections, statements, and best practices.
What is JDBC?
Core interfaces
The basic flow
Always use PreparedStatement
Connection pooling
Transactions
JDBC (Java Database Connectivity) is the standard Java API for talking to relational databases. Drivers translate your JDBC calls into the protocol of MySQL, PostgreSQL, Oracle, SQL Server, and others.
PreparedStatement separates SQL from data, eliminating SQL injection and improving performance through statement caching. Never concatenate user input into a query string.
Opening a connection is expensive. Use a pool — HikariCP is the default in Spring Boot — to reuse connections across requests. Set sensible maxPoolSize, connectionTimeout, and idleTimeout values.
- DriverManager / DataSource — get a Connection.
- Connection — represents a session with the database.
- Statement / PreparedStatement / CallableStatement — execute SQL.
- ResultSet — iterate query results.
- Obtain a Connection from a DataSource.
- Create a PreparedStatement with parameter placeholders.
- Bind parameters with setString, setInt, etc.
- Execute and iterate the ResultSet.
- Close everything — ideally with try-with-resources.
- Call setAutoCommit(false) to start manual control.
- Commit on success, rollback on exception.
- Pick the right isolation level for your use case.