JDBC in Java
JDBC (Java Database Connectivity) is the standard Java API for connecting to relational databases and running SQL. With JDBC, a Java program can open a connection to a database, send SQL statements such as SELECT and INSERT, and read the results. The API lives in the packages java.sql and javax.sql, which are part of the JDK. JDBC is database-independent: you write to the same interfaces whether the database is MySQL, PostgreSQL, Oracle or SQL Server, and a driver supplied by each database vendor does the real work. Frameworks such as Hibernate, Spring Data and MyBatis are all built on top of JDBC. In this lesson, you will learn why JDBC exists, how its parts fit together, and run your first query.
Why JDBC?
Every database speaks its own network protocol. Without a common API, a program written for MySQL would have to be rewritten for Oracle. JDBC solves this with one rule: your code talks to interfaces; the driver implements them.
| Without JDBC | With JDBC |
|---|---|
| Code tied to one database's own library | The same code works with any database that has a JDBC driver |
| A different API to learn for each database | One API: Connection, Statement, ResultSet |
| Switching databases means rewriting data access code | Switching mostly means a new driver and a new URL |
The JDBC Architecture
| Part | Role |
|---|---|
| Application | Your Java code. It uses only JDBC interfaces. |
| JDBC API | The interfaces and classes in java.sql and javax.sql. |
| DriverManager / DataSource | Finds the right driver for a URL and returns a Connection. |
| JDBC driver | A JAR from the database vendor that implements the interfaces for that database. |
| Database | Runs the SQL and returns results. |
The Main Interfaces and Classes
| Type | Description |
|---|---|
DriverManager | It is used to get a connection from a URL. |
DataSource | The modern way to get connections, usually from a pool. |
Connection | One session with the database. Creates statements and controls transactions. |
Statement | Runs a fixed SQL string. |
PreparedStatement | Runs SQL with ? parameters. Safer and usually faster. |
CallableStatement | Calls stored procedures. |
ResultSet | The rows returned by a query, read one at a time. |
ResultSetMetaData, DatabaseMetaData | Describe the columns of a result, and the database itself. |
SQLException | The exception thrown when something goes wrong. |
Example: A First Query
Let's see an example that creates a table, inserts three students and reads them back:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class FirstQuery {
public static void main(String[] args) throws Exception {
String url = "jdbc:h2:mem:school";
try (Connection con = DriverManager.getConnection(url);
Statement st = con.createStatement()) {
st.execute("CREATE TABLE student ("
+ "id INT PRIMARY KEY, name VARCHAR(50), marks INT)");
int rows = st.executeUpdate("INSERT INTO student VALUES "
+ "(1, 'Navika', 91), (2, 'Srihitha', 84), (3, 'Advitha', 78)");
System.out.println(rows + " rows inserted");
String sql = "SELECT id, name, marks FROM student "
+ "ORDER BY marks DESC";
try (ResultSet rs = st.executeQuery(sql)) {
while (rs.next()) {
System.out.println(rs.getInt("id") + " "
+ rs.getString("name") + " " + rs.getInt("marks"));
}
}
}
}
}3 rows inserted
1 Navika 91
2 Srihitha 84
3 Advitha 78Explanation:
- The URL
jdbc:h2:mem:schoolsays "use the H2 driver, an in-memory database named school". For MySQL it would look likejdbc:mysql://localhost:3306/school. DriverManager.getConnection(url)finds a driver that understands the URL and opens aConnection.createStatement()gives an object that can send SQL.executeUpdateruns SQL that changes data and returns how many rows were affected: 3.executeQueryruns aSELECTand returns aResultSet.rs.next()moves to the next row and returnsfalsewhen there are no more;getIntandgetStringread a column of the current row.- try-with-resources closes the
ResultSet, theStatementand theConnection, in that order.
JDBC Versions
| Version | Came with | Notable addition |
|---|---|---|
| JDBC 1 and 2 | JDK 1.1, 1.2 | The basic API; scrollable result sets; batch updates |
| JDBC 3 | Java 1.4 | Savepoints; generated keys |
| JDBC 4.0 | Java 6 | Drivers load automatically; no Class.forName needed |
| JDBC 4.1 | Java 7 | try-with-resources support |
| JDBC 4.2 | Java 8 | java.time types such as LocalDate |
| JDBC 4.3 | Java 9 | Sharding and other enterprise features |
The current version is 4.3.
Common Mistakes
Forgetting the driver JAR. JDBC is in the JDK, but the driver isn't. Without it you get "No suitable driver found".
Not closing connections. Each one uses resources in the database; leaks eventually stop the application from connecting at all.
Building SQL by joining strings with user input. This allows SQL injection; use PreparedStatement.
Interview Corner
What is JDBC?
JDBC (Java Database Connectivity) is the standard Java API for accessing relational databases. It defines interfaces such as Connection, Statement, PreparedStatement and ResultSet in java.sql and javax.sql. Database vendors provide drivers that implement these interfaces, so application code is independent of the database. A typical flow is: obtain a Connection from DriverManager or a DataSource, create a statement, execute SQL, process the ResultSet, and close the resources.
What are the main components of the JDBC architecture?
The application, the JDBC API, the driver manager (or a DataSource), the JDBC driver for a specific database, and the database itself. The application calls the API; the driver manager selects a driver based on the connection URL; the driver converts JDBC calls into the database's protocol.
Practice
- Easy: Add a fourth student to
FirstQueryand print only students with marks above 80. - Harder: Change the query to print the average marks using
SELECT AVG(marks) FROM student, reading the value withgetDouble(1).
Key Takeaways
Was this tutorial helpful?