// // Source File Name: GetData.java 1.3 // // Licensed Materials -- Property of IBM // // (c) Copyright International Business Machines Corporation, 1999. // All Rights Reserved. // // US Government Users Restricted Rights - // Use, duplication or disclosure restricted by // GSA ADP Schedule Contract with IBM Corp. // // This sample program shows a simple statement handle and how to // retrieve data from this statement. // For more information about this sample, refer to the README file. // For more information on Programming in Java, refer to the // "Programming in Java" section of the Application Development Guide. // For more information on building and running Java programs for DB2, // refer to the "Building Java Applets and Applications" section of the // Application Building Guide. // For more information on the SQL language, refer to the SQL Reference. import java.io.*; import java.lang.*; import java.sql.*; class GetData { static { try { // register the driver with DriverManager // The newInstance() call is needed for the sample to work with // JDK 1.1.1 on OS/2, where the Class.forName() method does not // run the static initializer. For other JDKs, the newInstance // call can be omitted. Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance(); } catch (Exception e) { e.printStackTrace(); } } public static void main (String[] argv) { Connection con = null; try { // connect using user id and password if (argv.length == 3) { // connect using command line arguments con = Tools.DBConnect(argv[0], argv[1], argv[2]); } else { // prompt user for database name, user ID, password con = Tools.DBConnect(); } con.setAutoCommit(false); displayDeptInformation (con); // disconnect from server and commit transactions System.out.println ("\n>Disconnecting..."); con.commit(); con.close(); } catch (Exception e) { e.printStackTrace(); } } // // displayDeptInformation // - executes a SELECT statement and displays results to screen // public static void displayDeptInformation (Connection con) { try { Statement stmt = con.createStatement(); // SQL Statement to select the department names and locations ResultSet rs = stmt.executeQuery ("SELECT deptname, location from org WHERE " + "division = 'Eastern'"); System.out.println ("\nDepartments in Eastern division:"); System.out.println ("DEPTNAME\t Location"); System.out.println ("---------------- --------------"); // rs.next() returns false when there are no more rows // retrieve data from the table and display the results while (rs.next()) { String dept = rs.getString (1); String loc = rs.getString (2); // formatted output System.out.println (Tools.padLength(dept, 17) + loc); } // close handles rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } } }