Example of sending a query to the HCL OneDB database

The following example shows how to use the PreparedStatement interface to execute a SELECT statement that has one input parameter:
try(PreparedStatement pstmt = conn.prepareStatement("SELECT tabid FROM systables WHERE tablid = ?") { 
   pstmt.setInt(1, 11);
   try(ResultSet r = pstmt.executeQuery()) {
      while(r.next()) {
         int i = r.getInt(1);
         System.out.println("Select: column tabid = " + i);
      }
   }
}
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.getInt() method, since the data type of the selected column is INTEGER.

Finally, both the ResultSet and PreparedStatement objects are implicitly closed with the appropriate using Java's try-with-resources block to close any object that implements java.lang.AutoCloseable

For more information about which getXXX() methods retrieve individual column values, see Data type mapping for ResultSet.getXXX() methods.