Queries using JDBC

The Statement object executes static queries, as well as statements that do not return result sets. For queries, you use the executeQuery method of the Statement object. This returns the result set in a ResultSet object.

The following code fragment illustrates how queries can be handled within JDBC. The code fragment places the total inventory value for a product into a variable named inventory. The product name is held in the String variable prodname. This example is available as the Query method of the JDBCExamples class.

The example assumes an internal or external connection has been obtained and is held in the Connection object named conn. It also assumes a variable

public static void Query () {
int max_price = 0;
    try{
      conn = DriverManager.getConnection( 
                   "jdbc:default:connection" );

      // Build the query
      String sqlStr =  "SELECT id, unit_price "
	+ "FROM product" ;

      // Execute the statement
      Statement stmt = conn.createStatement();
      ResultSet result = stmt.executeQuery( sqlStr );

      while( result.next() ) {
	int price = result.getInt(2);
	System.out.println( "Price is "  + price );
	if( price > max_price ) {
	  max_price = price ;
	}
      }
    }
    catch( Exception e ) {
      System.out.println("Error: " + e.getMessage());
      e.printStackTrace();
    }
      return max_price;
  }

Running the example

Once you have installed the JDBCExamples class into the sample database, you can execute this method using the following statement in Interactive SQL:

select JDBCExamples>>Query()

Notes