O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

24.4. The Essential JDBC Program

You now have all the pieces to make up the essential JDBC program, one that will initialize the environment, create Connection and Statement objects, and retrieve data by both position and column name.

Try It Out: Putting It All Together

This application will execute two queries, one that selects specific columns by name and another that selects all columns. First you'll define the application class in outline, with the data members and the main() function and the other methods in the class:

import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class EssentialJDBC {

  public static void main (String[] args) {
    EssentialJDBC SQLExample = new EssentialJDBC();   // Create application object

    SQLExample.getResultsByColumnName();
    SQLExample.getResultsByColumnPosition();
    SQLExample.getAllColumns();
    SQLExample.closeConnection();
  }

  public EssentialJDBC() {
    // Constructor to establish the connection and create a Statement object...
  }

  void getResultsByColumnName() {
    // Execute wildcard query and output selected columns...
  }

  void getResultsByColumnPosition() {
    // Execute ID and name query and output results...
} void getAllColumns() { // Execute wildcard query and output all columns... } // Close the connection void closeConnection() { if(connection != null) { try { connection.close(); connection = null; } catch (SQLException ex) { ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required