This Java code is a simple example of a JDBC application that executes a SELECT query against an SQL database. Bold type indicates source code that is likely to change if you execute the program against a different SQL database.
/****************************************************************************
* FILE NAME: selectex.java TITLE: SELECT PER (person) records
*
* AUTHOR: K. E. North II, Ken North Computing
*
* Copyright (c) Kendall E. North II, 1997. All rights reserved.
Reproduction
* or translation of this work beyond that permitted in Section
117 of the
* United States Copyright Act without express written permission
of the
* copyright owner is unlawful.
* The purchaser may make backup copies for his/her own use only
and not for
* distribution or resale. The Author and Publisher assume no
responsibility
* errors, omissions or damages caused by the use of these
programs or from
* use of the information contained herein.
*
***************************************************************************/
import java.sql.*;
class SelectFromPer {
public static void main(String
argv[]) {
try {
// Load the JDBC-ODBC bridge
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");// specify the ODBC data source's URL
String url = "jdbc:odbc:SSPer";
// connect
Connection con = DriverManager.getConnection(url,"North","Ken");// create and execute a SELECT
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT Surname,FirstName,Category FROM Per");System.out.println("Class is SelectFromPer\n");
// traverse through results
System.out.println("Found row:");
while (rs.next()) {
// get current row values
String Surname = rs.getString(1);
String FirstName = rs.getString(2);
int Category = rs.getInt(3);// print values
System.out.print (" Surname=" + Surname);
System.out.print (" FirstName=" + FirstName);
System.out.print (" Category=" + Category);
System.out.print(" \n");
}
// close statement and connection
stmt.close();
con.close();
} catch (java.lang.Exception ex) {ex.printStackTrace();
}
}
}
/******************** end of listing **************************/
For a simple JDBC Metadata example published in Dr. Dobb's Sourcebook, click here. For a server-side example (Java in the database) published in Web Techniques, click here.
updated October 13, 1998