A Simple Database Query Program
Listing 3.1 shows a simple JDBC query program. The database used for this example is the Cloudscape database, a 100% pure Java database available from http://www.cloudscape.com. The program puts together the various concepts you have already seen in this chapter.
Listing 3.1 Source Code for SimplyQuery.java
package usingj2ee.jdbc; import java.sql.*; public class SimpleQuery { public static void main(String[ ] args) { try { // Make sure the DriverManager knows about the driver Class.forName("COM.cloudscape.core.JDBCDriver"); // Create a connection to the database Connection conn = DriverManager.getConnection( "jdbc:cloudscape:j2eebook"); // Create a statement Statement stmt = conn.createStatement(); // Execute the query ResultSet results = stmt.executeQuery( "select * from person"); // Loop through all the results while (results.next()) { // Get the values from the result set String firstName = results.getString("first_name"); String middleName = results.getString("middle_name"); String lastName = results.getString("last_name"); int age = results.getInt("age"); // Print out the values System.out.println(firstName+" "+middleName+" "+lastName+ " "+age); } conn.close(); } catch (Exception exc) { exc.printStackTrace(); } } }
TIP
Don't forget to include the JDBC driver in your classpath before running the example. If you are using a database other than Cloudscape, you must also change both the driver name and the database URL.