JDBC Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.11

JdbcRowSet Query Statement with Parameters

This section describes how to define parameters in the query statement of a JdbcRowSet object.

When you call the setCommand() method to provide the SELECT query statement, you can define some parameters in the same way as a PreparedStatement. Here is a sample program showing you set parameters and provide parameter values:

/**
 * MySqlRowSetParameter.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import java.sql.*;
public class MySqlRowSetParameter {
  public static void main(String [] args) {
    try {

// Load the JDBC driver class. Needed for JDBC 3.0 drivers
      Class.forName("com.mysql.jdbc.Driver") ;

// Get a new JdbcRowSet object with Run's implementation
      javax.sql.rowset.JdbcRowSet jrs 
        = new com.sun.rowset.JdbcRowSetImpl();

// Set the connection URL for the DriverManager
      jrs.setUrl("jdbc:mysql://localhost/HerongDB"
        +"?user=Herong&password=TopSecret");

// Set a SQL statement with a parameter
      jrs.setCommand("SELECT * FROM Profile WHERE ID = ?");

// Set parameter values
      jrs.setInt(1, 90028);

// Connect and run the statement
      jrs.execute();
      jrs.next();
      System.out.println("User #90028: "
        +jrs.getString("FirstName")+" "+jrs.getString("LastName"));
      
// Repeating for another parameter value
      jrs.setInt(1, 90027);
      jrs.execute();
      jrs.next();
      System.out.println("User #90027: "
        +jrs.getString("FirstName")+" "+jrs.getString("LastName"));

// Close resource
      jrs.close();
    } catch (Exception e) {
      System.err.println("Exception: "+e.getMessage());
    }
  }
}

The parameter in this program represents the ID value in the Profile table. You may need to change the parameter values if your Profile table has different ID values. Here is the output of the program:

C:\>javac -cp .;\local\lib\rowset.jar MySqlRowSetParameter.java

MySqlRowSetParameter.java:15: 
warning: com.sun.rowset.JdbcRowSetImpl is Sun proprietary API 
and may be removed in a future release
        = new com.sun.rowset.JdbcRowSetImpl();
                            ^
1 warning

C:\>java -cp .;\local\lib\rowset.jar;
\local\lib\mysql-connector-java-5.0.7-bin.jar MySqlRowSetParameter
User #90028: 545 728d4
User #90027: 169b 1f61d

Sections in This Chapter

Overview of RowSet Objects

Installation of JdbcRowSet Reference Implementation

Connecting JdbcRowSet to Database Servers

Connecting JdbcRowSet with a Connection URL

Connecting JdbcRowSet with a Predefined Connection Object

Connecting JdbcRowSet with a Predefined ResultSet Object

Connecting JdbcRowSet with JNDI Directory Service

JdbcRowSet Query Statement with Parameters

Inserting Rows with JdbcRowSet Objects

Dr. Herong Yang, updated in 2007
JdbcRowSet Query Statement with Parameters