How To: Use SQL Databases in Java

Here is some sample code for use in a Java class. Note the special requirements in the comments at the top of the code. The customizable code is show in bold print. (Click here for an ODBC reference.)

// Sql.java -- sample program to read a database
// Configure the database for ODBC access using Start->Settings->Control Panel->ODBC32

import java.sql.*;

class Sql
{
  public static void main(String[] args)
  {
    // attempt to connect to the ODBC database
    String db = "myDatabase"; // ODBC database name
    System.out.println("Attempting to open database " + db + "...");
    Connection con = null;
    Statement stmt = null;
    try
    {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:" + db);
      stmt = con.createStatement();
    }
    catch (Exception ex)
    {
      // if not successful, quit
      System.out.println("Cannot open database -- make sure ODBC is configured properly.");
      System.exit(1);
    }

    // create a SQL statement
    String sql = "INSERT INTO courses (desig, term, units, grade) VALUES ('COMSC-265', 'FA2001', 4, 'A')";
    System.out.println("Executing " + sql);
    try
    {
      stmt.executeUpdate(sql);
    }
    catch (Exception ex)
    {
      // error executing SQL statement
      System.out.println("Error: " + ex);
    }

    // create another SQL statement
    sql = "SELECT desig,term,units,grade FROM courses";

    // execute the SQL statement
    System.out.println("Executing " + sql);
    ResultSet rs = null;
    try
    {
      rs = stmt.executeQuery(sql);
    }
    catch (Exception ex)
    {
      // error executing SQL statement
      System.out.println("Error: " + ex);
    }

    // if SQL statement is a SELECT statement, show records (skip for INSERT, DELETE, or UPDATE)
    System.out.println("Reading records returned by SQL statement...");
    try
    {
      while (rs.next())
      {
        String desig = rs.getString(1); // read 1st column as text
        String term = rs.getString(2); // read 2nd column as text
        int units = rs.getInt(3); // read 3rd column as int
        String grade = rs.getString(4); // read 4th column as text
        System.out.println(desig + ' ' + term + ' ' + units + ' ' + grade);
      }
    }
    catch (Exception ex)
    {
      // error executing SQL statement
      System.out.println("Error: " + ex);
    }

    // close database
    try
    {
      con.close();
    }
    catch (Exception ex){}

    System.out.println("Finished. Press ENTER to continue.");
  }
}


For ODBC DSN-Less Connections, use the following substitutions (e.g.):

String db = "DRIVER=Microsoft Access Driver (*.mdb);DBQ=c:\\Databases\\myDatabase.mdb";

Click here for other variations and other database formats.