Example of sending a query to the HCL OneDB database

The following example from the SimpleSelect.java program shows how to use the PreparedStatement interface to execute a SELECT statement that has one input parameter:
try
   {
   PreparedStatement pstmt = conn.prepareStatement("Select * 
      from x "
      + "where a = ?;");
   pstmt.setInt(1, 11);
   ResultSet r = pstmt.executeQuery();
   while(r.next())
      {
      short i = r.getShort(1);
      System.out.println("Select: column a = " + i);
      }
   r.close();
   pstmt.close();
   }
catch (SQLException e)
   {
   System.out.println("ERROR: Fetch statement failed: " +
      e.getMessage());
   }

The program first uses the Connection.prepareStatement() method to prepare the SELECT statement with its single input parameter. It then assigns a value to the parameter by using the PreparedStatement.setInt() method and executes the query with the PreparedStatement.executeQuery() method.

The program returns resulting rows in a ResultSet object, through which the program iterates with the ResultSet.next() method. The program retrieves individual column values with the ResultSet.getShort() method, since the data type of the selected column is SMALLINT.

Finally, both the ResultSet and PreparedStatement objects are explicitly closed with the appropriate close() method.

For more information about which getXXX() methods retrieve individual column values, see ids_jdbc_327.html#ids_jdbc_327.