⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 preparedstatement.java

📁 基于b/s的网上书店
💻 JAVA
📖 第 1 页 / 共 5 页
字号:

            try {
                byte[] parameterAsBytes = null;

                if (!this.isLoadDataQuery) {
                    parameterAsBytes = StringUtils.getBytes(parameterAsString,
                            this.charConverter, this.charEncoding);
                } else {
                    // Send with platform character encoding
                    parameterAsBytes = parameterAsString.getBytes();
                }

                setInternal(parameterIndex, parameterAsBytes);
            } catch (UnsupportedEncodingException uue) {
                throw new SQLException("Unsupported character encoding '"
                    + this.charEncoding + "'", SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
            }
        }
    }

    /**
     * Set a parameter to a java.sql.Time value.  The driver converts this to a
     * SQL TIME value when it sends it to the database.
     *
     * @param parameterIndex the first parameter is 1...));
     * @param x the parameter value
     *
     * @throws SQLException if a database access error occurs
     */
    public void setTime(int parameterIndex, Time x) throws SQLException {
        setTimeInternal(parameterIndex, x, this.connection.getDefaultTimeZone());
    }

    /**
     * Set a parameter to a java.sql.Time value.  The driver converts this to a
     * SQL TIME value when it sends it to the database.
     *
     * @param parameterIndex the first parameter is 1, the second is 2, ...
     * @param x the parameter value
     * @param cal the cal specifying the timezone
     *
     * @throws SQLException if a database-access error occurs.
     */
    public void setTime(int parameterIndex, java.sql.Time x, Calendar cal)
        throws SQLException {
        setTimeInternal(parameterIndex, x, cal.getTimeZone());
    }

    /**
     * Set a parameter to a java.sql.Timestamp value.  The driver converts this
     * to a SQL TIMESTAMP value when it sends it to the database.
     *
     * @param parameterIndex the first parameter is 1...
     * @param x the parameter value
     *
     * @throws SQLException if a database access error occurs
     */
    public void setTimestamp(int parameterIndex, Timestamp x)
        throws SQLException {
        setTimestampInternal(parameterIndex, x, this.connection.getDefaultTimeZone());
    }

    /**
     * Set a parameter to a java.sql.Timestamp value.  The driver converts this
     * to a SQL TIMESTAMP value when it sends it to the database.
     *
     * @param parameterIndex the first parameter is 1, the second is 2, ...
     * @param x the parameter value
     * @param cal the calendar specifying the timezone to use
     *
     * @throws SQLException if a database-access error occurs.
     */
    public void setTimestamp(int parameterIndex, java.sql.Timestamp x,
        Calendar cal) throws SQLException {
        setTimestampInternal(parameterIndex, x, cal.getTimeZone());
    }

    /**
     * @see PreparedStatement#setURL(int, URL)
     */
    public void setURL(int parameterIndex, URL arg) throws SQLException {
        if (arg != null) {
            setString(parameterIndex, arg.toString());
        } else {
            setNull(parameterIndex, Types.CHAR);
        }
    }

    /**
     * When a very large Unicode value is input to a LONGVARCHAR parameter, it
     * may be more practical to send it via a java.io.InputStream. JDBC will
     * read the data from the stream as needed, until it reaches end-of-file.
     * The JDBC driver will do any necessary conversion from UNICODE to the
     * database char format.
     * 
     * <P>
     * <B>Note:</B> This stream object can either be a standard Java stream
     * object or your own subclass that implements the standard interface.
     * </p>
     *
     * @param parameterIndex the first parameter is 1...
     * @param x the parameter value
     * @param length the number of bytes to read from the stream
     *
     * @throws SQLException if a database access error occurs
     *
     * @deprecated
     */
    public void setUnicodeStream(int parameterIndex, InputStream x, int length)
        throws SQLException {
        if (x == null) {
            setNull(parameterIndex, java.sql.Types.VARCHAR);
        } else {
            setBinaryStream(parameterIndex, x, length);
        }
    }

    /**
     * JDBC 2.0 Add a set of parameters to the batch.
     *
     * @throws SQLException if a database-access error occurs.
     *
     * @see Statement#addBatch
     */
    public void addBatch() throws SQLException {
        if (batchedArgs == null) {
            batchedArgs = new ArrayList();
        }

        batchedArgs.add(new BatchParams(parameterValues, parameterStreams,
                isStream, streamLengths, isNull));
    }

    /**
     * In general, parameter values remain in force for repeated used of a
     * Statement.  Setting a parameter value automatically clears its previous
     * value.  However, in some cases, it is useful to immediately release the
     * resources used by the current parameter values; this can be done by
     * calling clearParameters
     *
     * @throws SQLException if a database access error occurs
     */
    public void clearParameters() throws SQLException {
        for (int i = 0; i < parameterValues.length; i++) {
            parameterValues[i] = null;
            parameterStreams[i] = null;
            isStream[i] = false;
            isNull[i] = false;
        }
    }

    /**
     * Closes this prepared statement and releases all resources.
     *
     * @throws SQLException if database error occurs.
     */
    public void close() throws SQLException {
        super.close();

        this.parseInfo = null;
        this.dbmd = null;
        this.originalSql = null;
        this.staticSqlStrings = null;
        this.parameterValues = null;
        this.parameterStreams = null;
        this.isStream = null;
        this.streamLengths = null;
        this.isNull = null;
        this.streamConvertBuf = null;
    }

    /**
     * Some prepared statements return multiple results; the execute method
     * handles these complex statements as well as the simpler form of
     * statements handled by executeQuery and executeUpdate
     *
     * @return true if the next result is a ResultSet; false if it is an update
     *         count or there are no more results
     *
     * @throws SQLException if a database error occurs.
     */
    public boolean execute() throws SQLException {
        if (connection.isReadOnly() && (firstCharOfStmt != 'S')) {
            throw new SQLException("Connection is read-only. "
                + "Queries leading to data modification are not allowed",
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
        }

        checkClosed();

        ResultSet rs = null;

        synchronized (connection.getMutex()) {
            Buffer sendPacket = fillSendPacket();

            String oldCatalog = null;

            if (!this.connection.getCatalog().equals(currentCatalog)) {
                oldCatalog = this.connection.getCatalog();
                this.connection.setCatalog(currentCatalog);
            }

            boolean oldInfoMsgState = false;

            if (this.retrieveGeneratedKeys) {
                oldInfoMsgState = this.connection.isReadInfoMsgEnabled();
                this.connection.setReadInfoMsgEnabled(true);
            }

            // If there isn't a limit clause in the SQL
            // then limit the number of rows to return in
            // an efficient manner. Only do this if
            // setMaxRows() hasn't been used on any Statements
            // generated from the current Connection (saves
            // a query, and network traffic).
            //
            // Only apply max_rows to selects
            //
            if (this.connection.useMaxRows()) {
                if (firstCharOfStmt == 'S') {
                    if (hasLimitClause) {
                        rs = this.connection.execSQL((String) null, maxRows,
                                sendPacket, resultSetConcurrency,
                                createStreamingResultSet(), true,
                                this.currentCatalog);
                    } else {
                        if (maxRows <= 0) {
                            this.connection.execSQL("SET OPTION SQL_SELECT_LIMIT=DEFAULT",
                                -1, this.currentCatalog);
                        } else {
                            this.connection.execSQL(
                                "SET OPTION SQL_SELECT_LIMIT=" + maxRows, -1,
                                this.currentCatalog);
                        }
                    }
                } else {
                    this.connection.execSQL("SET OPTION SQL_SELECT_LIMIT=DEFAULT",
                        -1, this.currentCatalog);
                }

                // Finally, execute the query
                rs = this.connection.execSQL(null, -1, sendPacket,
                        resultSetConcurrency, createStreamingResultSet(),
                        (firstCharOfStmt == 'S'), this.currentCatalog);
            } else {
                rs = this.connection.execSQL(null, -1, sendPacket,
                        resultSetConcurrency, createStreamingResultSet(),
                        (firstCharOfStmt == 'S'), this.currentCatalog);
            }

            if (this.retrieveGeneratedKeys) {
                this.connection.setReadInfoMsgEnabled(oldInfoMsgState);
            }

            if (oldCatalog != null) {
                this.connection.setCatalog(oldCatalog);
            }
        }

        lastInsertId = rs.getUpdateID();

        if (rs != null) {
            this.results = rs;
        }

        rs.setFirstCharOfQuery(this.firstCharOfStmt);
        rs.setConnection(connection);
        rs.setResultSetType(resultSetType);
        rs.setResultSetConcurrency(resultSetConcurrency);
        rs.setStatement(this);

        return ((rs != null) && rs.reallyResult());
    }

    /**
     * JDBC 2.0 Submit a batch of commands to the database for execution. This
     * method is optional.
     *
     * @return an array of update counts containing one element for each
     *         command in the batch.  The array is ordered according to the
     *         order in which commands were inserted into the batch
     *
     * @throws SQLException if a database-access error occurs, or the driver
     *         does not support batch statements
     * @throws java.sql.BatchUpdateException DOCUMENT ME!
     */
    public int[] executeBatch() throws SQLException {
        if (connection.isReadOnly()) {
            throw new SQLException("Connection is read-only. "
                + "Queries leading to data modification are not allowed",
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
        }

        try {
            int[] updateCounts = null;

            if (batchedArgs != null) {
                int nbrCommands = batchedArgs.size();
                updateCounts = new int[nbrCommands];

                for (int i = 0; i < nbrCommands; i++) {
                    updateCounts[i] = -3;
                }

                SQLException sqlEx = null;

                int commandIndex = 0;

                for (commandIndex = 0; commandIndex < nbrCommands;
                        commandIndex++) {
                    Object arg = batchedArgs.get(commandIndex);

                    if (arg instanceof String) {
                        updateCounts[commandIndex] = executeUpdate((String) arg);
                    } else {
                        BatchParams paramArg = (BatchParams) arg;

                        try {
                            updateCounts[commandIndex] = executeUpdate(paramArg.parameterStrings,
                                    paramArg.parameterStreams,
                                    paramArg.isStream, paramArg.streamLengths,
                                    paramArg.isNull);
                        } catch (SQLException ex) {
                            updateCounts[commandIndex] = EXECUTE_FAILED;

                            if (this.connection.continueBatchOnError()) {
                                sqlEx = ex;
                            } else {
                                int[] newUpdateCounts = new int[commandIndex];
                                System.arraycopy(updateCounts, 0,
                                    newUpdateCounts, 0, commandIndex);

                                throw new java.sql.BatchUpdateException(ex
                                    .getMessage(), ex.getSQLState(),
                                    ex.getErrorCode(), newUpdateCounts);
                            }
                        }
                    }
                }

                if (sqlEx != null) {
                    throw new java.sql.BatchUpdateException(sqlEx.getMessage(),
                        sqlEx.getSQLState(), sqlEx.getErrorCode(), updateCounts);
                }
            }

            return (updateCounts != null) ? updateCounts : new int[0];
        } finally {
            clearBatch();
        }
    }

    /**
     * A Prepared SQL query is executed and its ResultSet is returned

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -