Computer Science 122

Assignment 2

Due: September 21, 2004

 

Write a program in Java that will connect to your database and display the results on the screen.  Follow the example in the handout or the one listed below.  Show your display in class and hand in a printout of the program.

 

// Produce connects to a database and displays its contents on the screen.

import java.sql.*;

 

public class Produce

{

       public static void main (String [] args) throws Exception

       {

               // // Open a connection to the database.

               Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");

               Connection con = DriverManager.getConnection ("jdbc:odbc:produce");

 

               // Create a statement object and use it to query the database.

               Statement stmt = con.createStatement ();

               String query = "Select * From ProduceTable";

 

               // Get the results from the query and display them on the screen.

               ResultSet rs = stmt.executeQuery (query);

               System.out.println ("Produce Table Results");

               while (rs.next ())

               {

                      System.out.println (rs.getString ("ID")); // The datatype of these fields is Text.

                      System.out.println (rs.getString ("Type"));

                      System.out.println (rs.getString ("Name"));

                      System.out.println (rs.getString ("Variety"));

                      System.out.println (rs.getDouble ("Price"));   // The datatype of the Price field is Currency.

                      System.out.println ();

               }

               con.close ();

       } // main

} // Produce

 

 

A picture of the database table.