Learning about parameters in a PreparedStatement using ParameterMetaData methods
The IBM® Data Server Driver for JDBC and SQLJ includes support for the ParameterMetaData interface. The ParameterMetaData interface contains methods that retrieve information about the parameter markers in a PreparedStatement object.
About this task
ParameterMetaData methods provide
the following types of information:
- The data types of parameters, including the precision and scale of decimal parameters.
- The parameters' database-specific type names. For parameters that correspond to table columns that are defined with distinct types, these names are the distinct type names.
- Whether parameters are nullable.
- Whether parameters are input or output parameters.
- Whether the values of a numeric parameter can be signed.
- The fully-qualified Java™ class name that PreparedStatement.setObject uses when it sets a parameter value.
Procedure
To invoke ParameterMetaData methods, you need to perform these basic steps:
- Invoke the Connection.prepareStatement method to create a PreparedStatement object.
- Invoke the PreparedStatement.getParameterMetaData method to retrieve a ParameterMetaData object.
- Invoke ParameterMetaData.getParameterCount to determine the number of parameters in the PreparedStatement.
- Invoke ParameterMetaData methods on individual parameters.
Example
Connection con;
ParameterMetaData pmtadta;
int mtadtacnt;
String sqlType;
…
pstmt = con.prepareStatement(
"UPDATE EMPLOYEE SET PHONENO=? WHERE EMPNO=?");
// Create a PreparedStatement object 1
pmtadta = pstmt.getParameterMetaData(); 2
// Create a ParameterMetaData object
mtadtacnt = pmtadta.getParameterCount(); 3
// Determine the number of parameters
System.out.println("Number of statement parameters: " + mtadtacnt);
for (int i = 1; i <= mtadtacnt; i++) {
sqlType = pmtadta.getParameterTypeName(i); 4
// Get SQL type for each parameter
System.out.println("SQL type of parameter " + i " is " + sqlType);
}
…
pstmt.close(); // Close the PreparedStatement