5 Steps to Connect to a Database in Java

Naveen AnamaneniUpdated · 5 min read

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

StepWhat it doesCode
1Load (register) the driverClass.forName("org.h2.Driver") (optional since JDBC 4.0)
2Open a connectionDriverManager.getConnection(url, user, password)
3Create a statementcon.createStatement() or con.prepareStatement(sql)
4Execute SQL and process resultsexecuteQuery, executeUpdate, then read the ResultSet
5Close the resourcesrs.close(), st.close(), con.close()

Example: The Classic Form

FiveSteps.java▶ Try it
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());
    }
}
Output
Connected: true
J101 -> Core Java
Closed: true

Explanation:

  1. Class.forName loads the driver class, which registers itself with DriverManager. 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.
  2. getConnection(url, user, password) opens the connection. sa with an empty password is H2's default user.
  3. createStatement() returns a Statement bound to that connection.
  4. executeUpdate runs SQL that changes something; executeQuery runs a SELECT. Columns can be read by position, getString(1), starting at 1, or by name.
  5. 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:

Modern.java
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"));
    }
}
StepClassicModern
1. Load the driverClass.forName(...)Automatic
2. Open a connectionDriverManager.getConnectionThe same, inside try (...)
3. Create a statementcreateStatement()The same, inside try (...)
4. Execute and processThe sameThe same
5. CloseManual, in a finally blockAutomatic

The Connection URL

The URL in step 2 has the general form jdbc:<database>:<location and options>:

DatabaseExample URL
MySQLjdbc:mysql://localhost:3306/school
PostgreSQLjdbc:postgresql://localhost:5432/school
Oraclejdbc:oracle:thin:@//localhost:1521/XEPDB1
SQL Serverjdbc: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

  1. Easy: Rewrite FiveSteps using try-with-resources and remove the Class.forName line.
  2. Harder: Deliberately misspell the table name in the query, catch the SQLException, and print its message and getSQLState().

Quick check: Five steps

4 questions
1Which step is optional since JDBC 4.0?
2What is the index of the first column in a ResultSet?
3In which order should resources be closed?
4What does try-with-resources add?

Key Takeaways

Was this tutorial helpful?

Lesson 485 of 578