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) { ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.