详解如何获取PreparedStatement参数示例详解

 更新时间:2023年09月06日 10:30:41   作者:codecraft  
这篇文章主要为大家介绍了详解如何获取PreparedStatement参数示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

本文主要研究一下如何获取PreparedStatement的参数

PreparedStatement

java/sql/PreparedStatement.java

public interface PreparedStatement extends Statement {
     void setNull(int parameterIndex, int sqlType) throws SQLException;
     void setBoolean(int parameterIndex, boolean x) throws SQLException;
     void setInt(int parameterIndex, int x) throws SQLException;
     void setLong(int parameterIndex, long x) throws SQLException;
     //......
    default void setObject(int parameterIndex, Object x, SQLType targetSqlType,
             int scaleOrLength) throws SQLException {
        throw new SQLFeatureNotSupportedException("setObject not implemented");
    }
    default void setObject(int parameterIndex, Object x, SQLType targetSqlType)
      throws SQLException {
        throw new SQLFeatureNotSupportedException("setObject not implemented");
    }
    /**
     * Retrieves the number, types and properties of this
     * <code>PreparedStatement</code> object's parameters.
     *
     * @return a <code>ParameterMetaData</code> object that contains information
     *         about the number, types and properties for each
     *  parameter marker of this <code>PreparedStatement</code> object
     * @exception SQLException if a database access error occurs or
     * this method is called on a closed <code>PreparedStatement</code>
     * @see ParameterMetaData
     * @since 1.4
     */
    ParameterMetaData getParameterMetaData() throws SQLException;
}
PreparedStatement继承了Statement接口,它主要是多定义了一系列的set方法,但是没有定义get方法,只是定义了getParameterMetaData方法返回ParameterMetaData

ParameterMetaData

java/sql/ParameterMetaData.java

public interface ParameterMetaData extends Wrapper {
    /**
     * Retrieves the number of parameters in the <code>PreparedStatement</code>
     * object for which this <code>ParameterMetaData</code> object contains
     * information.
     *
     * @return the number of parameters
     * @exception SQLException if a database access error occurs
     * @since 1.4
     */
    int getParameterCount() throws SQLException;
    /**
     * Retrieves whether null values are allowed in the designated parameter.
     *
     * @param param the first parameter is 1, the second is 2, ...
     * @return the nullability status of the given parameter; one of
     *        <code>ParameterMetaData.parameterNoNulls</code>,
     *        <code>ParameterMetaData.parameterNullable</code>, or
     *        <code>ParameterMetaData.parameterNullableUnknown</code>
     * @exception SQLException if a database access error occurs
     * @since 1.4
     */
    int isNullable(int param) throws SQLException;
    /**
     * The constant indicating that a
     * parameter will not allow <code>NULL</code> values.
     */
    int parameterNoNulls = 0;
    /**
     * The constant indicating that a
     * parameter will allow <code>NULL</code> values.
     */
    int parameterNullable = 1;
    /**
     * The constant indicating that the
     * nullability of a parameter is unknown.
     */
    int parameterNullableUnknown = 2;
    /**
     * Retrieves whether values for the designated parameter can be signed numbers.
     *
     * @param param the first parameter is 1, the second is 2, ...
     * @return <code>true</code> if so; <code>false</code> otherwise
     * @exception SQLException if a database access error occurs
     * @since 1.4
     */
    boolean isSigned(int param) throws SQLException;
    /**
     * Retrieves the designated parameter's specified column size.
     *
     * <P>The returned value represents the maximum column size for the given parameter.
     * For numeric data, this is the maximum precision.  For character data, this is the length in characters.
     * For datetime datatypes, this is the length in characters of the String representation (assuming the
     * maximum allowed precision of the fractional seconds component). For binary data, this is the length in bytes.  For the ROWID datatype,
     * this is the length in bytes. 0 is returned for data types where the
     * column size is not applicable.
     *
     * @param param the first parameter is 1, the second is 2, ...
     * @return precision
     * @exception SQLException if a database access error occurs
     * @since 1.4
     */
    int getPrecision(int param) throws SQLException;
    /**
     * Retrieves the designated parameter's number of digits to right of the decimal point.
     * 0 is returned for data types where the scale is not applicable.
     *
     * @param param the first parameter is 1, the second is 2, ...
     * @return scale
     * @exception SQLException if a database access error occurs
     * @since 1.4
     */
    int getScale(int param) throws SQLException;
    /**
     * Retrieves the designated parameter's SQL type.
     *
     * @param param the first parameter is 1, the second is 2, ...
     * @return SQL type from <code>java.sql.Types</code>
     * @exception SQLException if a database access error occurs
     * @since 1.4
     * @see Types
     */
    int getParameterType(int param) throws SQLException;
    /**
     * Retrieves the designated parameter's database-specific type name.
     *
     * @param param the first parameter is 1, the second is 2, ...
     * @return type the name used by the database. If the parameter type is
     * a user-defined type, then a fully-qualified type name is returned.
     * @exception SQLException if a database access error occurs
     * @since 1.4
     */
    String getParameterTypeName(int param) throws SQLException;
    /**
     * Retrieves the fully-qualified name of the Java class whose instances
     * should be passed to the method <code>PreparedStatement.setObject</code>.
     *
     * @param param the first parameter is 1, the second is 2, ...
     * @return the fully-qualified name of the class in the Java programming
     *         language that would be used by the method
     *         <code>PreparedStatement.setObject</code> to set the value
     *         in the specified parameter. This is the class name used
     *         for custom mapping.
     * @exception SQLException if a database access error occurs
     * @since 1.4
     */
    String getParameterClassName(int param) throws SQLException;
    /**
     * The constant indicating that the mode of the parameter is unknown.
     */
    int parameterModeUnknown = 0;
    /**
     * The constant indicating that the parameter's mode is IN.
     */
    int parameterModeIn = 1;
    /**
     * The constant indicating that the parameter's mode is INOUT.
     */
    int parameterModeInOut = 2;
    /**
     * The constant indicating that the parameter's mode is  OUT.
     */
    int parameterModeOut = 4;
    /**
     * Retrieves the designated parameter's mode.
     *
     * @param param the first parameter is 1, the second is 2, ...
     * @return mode of the parameter; one of
     *        <code>ParameterMetaData.parameterModeIn</code>,
     *        <code>ParameterMetaData.parameterModeOut</code>, or
     *        <code>ParameterMetaData.parameterModeInOut</code>
     *        <code>ParameterMetaData.parameterModeUnknown</code>.
     * @exception SQLException if a database access error occurs
     * @since 1.4
     */
    int getParameterMode(int param) throws SQLException;
}
ParameterMetaDatat提供了getParameterCount、getParameterType、getParameterTypeName、getParameterClassName、getParameterMode

com.mysql.jdbc.PreparedStatement

com/mysql/jdbc/PreparedStatement.java

public class PreparedStatement extends com.mysql.jdbc.StatementImpl implements
        java.sql.PreparedStatement {
    //......
    protected int parameterCount;
    protected MysqlParameterMetadata parameterMetaData;
    private InputStream[] parameterStreams = null;
    private byte[][] parameterValues = null;
    /**
     * Only used by statement interceptors at the moment to
     * provide introspection of bound values
     */
    protected int[] parameterTypes = null;
    public ParameterBindings getParameterBindings() throws SQLException {
        synchronized (checkClosed()) {
            return new EmulatedPreparedStatementBindings();
        }
    }
    //......
}
mysql的PreparedStatement实现定义了parameterCount、parameterMetaData、parameterStreams、parameterValues、parameterTypes属性,提供了getParameterBindings方法,返回的是EmulatedPreparedStatementBindings

ParameterBindings

com/mysql/jdbc/ParameterBindings.java

public interface ParameterBindings {
    public abstract Array getArray(int parameterIndex) throws SQLException;
    public abstract InputStream getAsciiStream(int parameterIndex) throws SQLException;
    public abstract BigDecimal getBigDecimal(int parameterIndex) throws SQLException;
    public abstract InputStream getBinaryStream(int parameterIndex) throws SQLException;
    public abstract java.sql.Blob getBlob(int parameterIndex) throws SQLException;
    public abstract boolean getBoolean(int parameterIndex) throws SQLException;
    public abstract byte getByte(int parameterIndex) throws SQLException;
    public abstract byte[] getBytes(int parameterIndex) throws SQLException;
    public abstract Reader getCharacterStream(int parameterIndex) throws SQLException;
    public abstract Clob getClob(int parameterIndex) throws SQLException;
    public abstract Date getDate(int parameterIndex) throws SQLException;
    public abstract double getDouble(int parameterIndex) throws SQLException;
    public abstract float getFloat(int parameterIndex) throws SQLException;
    public abstract int getInt(int parameterIndex) throws SQLException;
    public abstract long getLong(int parameterIndex) throws SQLException;
    public abstract Reader getNCharacterStream(int parameterIndex) throws SQLException;
    public abstract Reader getNClob(int parameterIndex) throws SQLException;
    public abstract Object getObject(int parameterIndex) throws SQLException;
    public abstract Ref getRef(int parameterIndex) throws SQLException;
    public abstract short getShort(int parameterIndex) throws SQLException;
    public abstract String getString(int parameterIndex) throws SQLException;
    public abstract Time getTime(int parameterIndex) throws SQLException;
    public abstract Timestamp getTimestamp(int parameterIndex) throws SQLException;
    public abstract URL getURL(int parameterIndex) throws SQLException;
    public abstract boolean isNull(int parameterIndex) throws SQLException;
}
ParameterBindings定义了一系列的get方法

EmulatedPreparedStatementBindings

class EmulatedPreparedStatementBindings implements ParameterBindings {
        private ResultSetImpl bindingsAsRs;
        private boolean[] parameterIsNull;
        EmulatedPreparedStatementBindings() throws SQLException {
            List<ResultSetRow> rows = new ArrayList<ResultSetRow>();
            parameterIsNull = new boolean[parameterCount];
            System
                    .arraycopy(isNull, 0, this.parameterIsNull, 0,
                            parameterCount);
            byte[][] rowData = new byte[parameterCount][];
            Field[] typeMetadata = new Field[parameterCount];
            for (int i = 0; i < parameterCount; i++) {
                if (batchCommandIndex == -1)
                    rowData[i] = getBytesRepresentation(i);
                else
                    rowData[i] = getBytesRepresentationForBatch(i, batchCommandIndex);
                int charsetIndex = 0;
                if (parameterTypes[i] == Types.BINARY
                        || parameterTypes[i] == Types.BLOB) {
                    charsetIndex = 63;
                } else {
                    try {
                        String mysqlEncodingName = CharsetMapping
                                .getMysqlEncodingForJavaEncoding(connection
                                        .getEncoding(), connection);
                        charsetIndex = CharsetMapping
                                .getCharsetIndexForMysqlEncodingName(mysqlEncodingName);
                    } catch (SQLException ex) {
                        throw ex;
                    } catch (RuntimeException ex) {
                        SQLException sqlEx = SQLError.createSQLException(ex.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, null);
                        sqlEx.initCause(ex);
                        throw sqlEx;
                    }
                }
                Field parameterMetadata = new Field(null, "parameter_"
                        + (i + 1), charsetIndex, parameterTypes[i],
                        rowData[i].length);
                parameterMetadata.setConnection(connection);
                typeMetadata[i] = parameterMetadata;
            }
            rows.add(new ByteArrayRow(rowData, getExceptionInterceptor()));
            this.bindingsAsRs = new ResultSetImpl(connection.getCatalog(),
                    typeMetadata, new RowDataStatic(rows), connection, null);
            this.bindingsAsRs.next();
        }
        //......
    }
EmulatedPreparedStatementBindings实现了ParameterBindings接口,它主要是把参数组装到rowData,然后创建了RowDataStatic,构造ResultSetImpl这个对象来实现

小结

jdbc的PreparedStatement并未提供相应的get参数的方法,只能从driver的实现类去找,比如mysql的PreparedStatement实现提供了getParameterBindings方法,返回的是EmulatedPreparedStatementBindings,可以获取参数

以上就是详解如何获取PreparedStatement参数示例详解的详细内容,更多关于PreparedStatement参数获取的资料请关注脚本之家其它相关文章!

相关文章

  • Java长度不足左位补0的3种实现方法

    Java长度不足左位补0的3种实现方法

    这篇文章主要介绍了Java长度不足左位补0的3种实现方法小结,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • Java实现五子棋游戏

    Java实现五子棋游戏

    这篇文章主要为大家详细介绍了Java实现五子棋游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-04-04
  • Java Stream流零基础教程

    Java Stream流零基础教程

    Java8的另一大亮点Stream,它与java.io包里的InputStream和OutputStream是完全不同的概念,下面这篇文章主要给大家介绍了关于Java8中Stream详细使用方法的相关资料,需要的朋友可以参考下
    2022-11-11
  • Java的Struts框架中配置国际化的资源存储的要点解析

    Java的Struts框架中配置国际化的资源存储的要点解析

    这篇文章主要介绍了Java的Struts框架中配置国际化的资源存储的要点解析,针对用户所使用的语言来配置资源文件,需要的朋友可以参考下
    2016-04-04
  • java基础详细笔记之异常处理

    java基础详细笔记之异常处理

    异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免的,下面这篇文章主要给大家介绍了关于java基础详细笔记之异常处理的相关资料,需要的朋友可以参考下
    2022-03-03
  • No ‘Access-Control-Allow-Origin‘ header is present跨域及解决

    No ‘Access-Control-Allow-Origin‘ header is&nb

    这篇文章主要介绍了No ‘Access-Control-Allow-Origin‘ header is present跨域及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • java合成模式之神奇的树结构

    java合成模式之神奇的树结构

    这篇文章主要介绍了java合成模式,文中运用大量的代码进行详细讲解,希望大家看完本文后能学习到相关的知识,需要的朋友可以参考一下
    2021-08-08
  • Springboot项目快速实现拦截器功能

    Springboot项目快速实现拦截器功能

    上一篇文章介绍了Springboot项目如何快速实现过滤器功能,本篇文章接着来盘一盘拦截器,仔细研究后会发现,其实拦截器和过滤器的功能非常类似,可以理解为面向切面编程的一种具体实现。感兴趣的小伙伴可以参考阅读
    2023-03-03
  • SpringBoot之那些注入不了的Spring占位符(${}表达式)问题

    SpringBoot之那些注入不了的Spring占位符(${}表达式)问题

    这篇文章主要介绍了SpringBoot之那些注入不了的Spring占位符(${}表达式)问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04
  • 如何使用stream从List对象中获取某列数据

    如何使用stream从List对象中获取某列数据

    这篇文章主要介绍了如何使用stream从List对象中获取某列数据问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12

最新评论