5 Steps to Connect to a Database in Java
Every JDBC program follows the same five steps to work with a database: load the driver, open a connection, create a statement, execute SQL and process the results, and close the resources. Textbooks and interviewers have described JDBC this way for decades. Modern Java has made two of the steps almost invisible: drivers load automatically, and try-with-resources closes everything for you. In this lesson, you will learn each step, see the classic form, and then the shorter form you should write today.
The Five Steps
| Step | What it does | Code |
|---|---|---|
| 1 | Load (register) the driver | Class.forName("org.h2.Driver") (optional since JDBC 4.0) |
| 2 | Open a connection | DriverManager.getConnection(url, user, password) |
| 3 | Create a statement | con.createStatement() or con.prepareStatement(sql) |
| 4 | Execute SQL and process results | executeQuery, executeUpdate, then read the ResultSet |
| 5 | Close the resources | rs.close(), st.close(), con.close() |
Example: The Classic Form
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class FiveSteps {
public static void main(String[] args) throws Exception {
// Step 1: load the driver (optional since JDBC 4.0).
Class.forName("org.h2.Driver");
// Step 2: open a connection.
Connection con = DriverManager.getConnection(
"jdbc:h2:mem:school", "sa", "");
System.out.println("Connected: " + !con.isClosed());
// Step 3: create a statement.
Statement st = con.createStatement();
// Step 4: run SQL and read the results.
st.executeUpdate("CREATE TABLE course ("
+ "code VARCHAR(10), title VARCHAR(40))");
st.executeUpdate("INSERT INTO course VALUES ('J101', 'Core Java')");
ResultSet rs = st.executeQuery("SELECT code, title FROM course");
while (rs.next()) {
System.out.println(rs.getString(1) + " -> " + rs.getString(2));
}
// Step 5: close everything, newest first.
rs.close();
st.close();
con.close();
System.out.println("Closed: " + con.isClosed());
}
}Connected: true
J101 -> Core Java
Closed: trueExplanation:
Class.forNameloads the driver class, which registers itself withDriverManager. With a JDBC 4 driver on the class path this line can be deleted; it is shown because older code and many interview answers include it.getConnection(url, user, password)opens the connection.sawith an empty password is H2's default user.createStatement()returns aStatementbound to that connection.executeUpdateruns SQL that changes something;executeQueryruns aSELECT. Columns can be read by position,getString(1), starting at 1, or by name.- Closing happens in the reverse order of opening: result set, statement, connection.
The Problem with the Classic Form
If any line between opening and closing throws an exception, the close() calls are skipped and the connection leaks. The old fix was a long finally block with a null check and a try/catch around every close().
The Modern Form
try-with-resources closes each resource automatically, in reverse order, even when an exception is thrown:
String url = "jdbc:h2:mem:school";
try (Connection con = DriverManager.getConnection(url, "sa", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT code, title FROM course")) {
while (rs.next()) {
System.out.println(rs.getString("code") + " -> "
+ rs.getString("title"));
}
}| Step | Classic | Modern |
|---|---|---|
| 1. Load the driver | Class.forName(...) | Automatic |
| 2. Open a connection | DriverManager.getConnection | The same, inside try (...) |
| 3. Create a statement | createStatement() | The same, inside try (...) |
| 4. Execute and process | The same | The same |
| 5. Close | Manual, in a finally block | Automatic |
The Connection URL
The URL in step 2 has the general form jdbc:<database>:<location and options>:
| Database | Example URL |
|---|---|
| MySQL | jdbc:mysql://localhost:3306/school |
| PostgreSQL | jdbc:postgresql://localhost:5432/school |
| Oracle | jdbc:oracle:thin:@//localhost:1521/XEPDB1 |
| SQL Server | jdbc:sqlserver://localhost:1433;databaseName=school |
| H2 (in memory) | jdbc:h2:mem:school |
Common Mistakes
Closing in the wrong order, or not at all. Use try-with-resources and stop worrying about it.
Reading columns from index 0. JDBC columns start at 1; index 0 throws SQLException.
Calling a getter before rs.next(). The cursor starts before the first row.
Catching SQLException and printing nothing. Its message, getSQLState() and getErrorCode() tell you what went wrong.
Interview Corner
What are the steps to connect to a database using JDBC?
(1) Load and register the driver, traditionally with Class.forName(driverClass); this is automatic for JDBC 4 drivers on the class path. (2) Establish a connection with DriverManager.getConnection(url, user, password) or from a DataSource. (3) Create a Statement, PreparedStatement or CallableStatement from the connection. (4) Execute the SQL with executeQuery or executeUpdate and process the ResultSet. (5) Close the ResultSet, statement and connection, best done with try-with-resources.
Practice
- Easy: Rewrite
FiveStepsusing try-with-resources and remove theClass.forNameline. - Harder: Deliberately misspell the table name in the query, catch the
SQLException, and print its message andgetSQLState().
Key Takeaways
Was this tutorial helpful?