JDBC Tutorial - JDBC HelloWorld








The following sections show how to create a simple JDBC application.

It will show you how to open a database connection, execute a SQL query, and display the results.

We need to follow the following steps to building a JDBC application:

  • Register the JDBC driver
  • Open a connection
  • Execute a sql command, for example a query or an update statement
  • Extract data from result set after query
  • Clean up the environment




Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*www  .j a  va 2s .com*/
public class Main {
  // JDBC driver name and database URL
  static final String JDBC_DRIVER = "org.hsqldb.jdbcDriver";
  static final String DB_URL = "jdbc:hsqldb:mem:db_file";

  // Database credentials
  static final String USER = "sa";
  static final String PASS = "";

  public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    try {
      // Register JDBC driver
      Class.forName(JDBC_DRIVER);

      // Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);

      // Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      stmt.executeUpdate("CREATE TABLE Employees ( id INTEGER IDENTITY, first VARCHAR(256),  last VARCHAR(256),age INTEGER)");
      stmt.executeUpdate("INSERT INTO Employees VALUES(1,'Jack','Smith', 100)");

      ResultSet rs = stmt.executeQuery(sql);

      // Extract data from result set
      while (rs.next()) {
        // Retrieve by column name
        int id = rs.getInt("id");
        int age = rs.getInt("age");
        String first = rs.getString("first");
        String last = rs.getString("last");

        System.out.print("ID: " + id);
        System.out.print(", Age: " + age);
        System.out.print(", First: " + first);
        System.out.println(", Last: " + last);
      }
      // Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
    } catch (SQLException se) {
      se.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // finally block used to close resources
      try {
        if (stmt != null)
          stmt.close();
      } catch (SQLException se2) {
      }
      try {
        if (conn != null)
          conn.close();
      } catch (SQLException se) {
        se.printStackTrace();
      }
    }
    System.out.println("Goodbye!");
  }
}




Note

The following code uses the hsql database as the relational database engine.

hsql database is a pure Java language based database, which means the database system is written in Java language. Therefore the whole database system and JDBC driver is all included in a jar file.

The JDBC driver name for hsql is org.hsqldb.jdbcDriver.

The URL we used to connect to database to hsql database is jdbc:hsqldb:mem:db_file.

mem in the URL tells the hsql database sytem to create a memory based table. So we can execute the create table statement again and again.

The user name to connect to the hsql database is sa and the password is left empty.

USER = "sa";
PASS = "";


Download JDBC_HSQL_Helloword.zip