home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book Home Java Enterprise in a Nutshell Search this book

2.2. JDBC Basics

Before we discuss all of the individual components of JDBC, let's look at a simple example that incorporates most of the major pieces of JDBC functionality. Example 2-1 loads a driver, connects to the database, executes some SQL, and retrieves the results. It also keeps an eye out for any database-related errors.

Example 2-1. A Simple JDBC Example

import java.sql.*;

public class JDBCSample {

  public static void main(java.lang.String[] args) {
    try {
      // This is where we load the driver
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } 
    catch (ClassNotFoundException e) {
      System.out.println("Unable to load Driver Class");
      return;
    }
  
    try {
      // All database access is within a try/catch block. Connect to database,
      // specifying particular database, username, and password
      Connection con = DriverManager.getConnection("jdbc:odbc:companydb",
                       "", "");
   
      // Create and execute an SQL Statement
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("SELECT FIRST_NAME FROM EMPLOYEES");

      // Display the SQL Results
      while(rs.next()) {
        System.out.println(rs.getString("FIRST_NAME"));
      }

      // Make sure our database resources are released
      rs.close();
      stmt.close();
      con.close();

    } 
    catch (SQLException se) {
      // Inform user of any SQL errors
      System.out.println("SQL Exception: " + se.getMessage());
      se.printStackTrace(System.out);
    } 
  } 
}

Example 2-1 starts out by loading a JDBC driver class (in this case, Sun's JDBC-ODBC Bridge). Then it creates a database connection, represented by a Connection object, using that driver. With the database connection, we can create a Statement object to represent an SQL statement. Executing an SQL statement produces a ResultSet that contains the results of a query. The program displays the results and then cleans up the resources it has used. If an error occurs, a SQLException is thrown, so our program traps that exception and displays some of the information it encapsulates.

Clearly, there is a lot going on in this simple program. Every Java application that uses JDBC follows these basic steps, so the following sections discuss each step in much more detail.



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.