📄 preparedstatement.java
字号:
&& this.connection.getNetTimeoutForStreamingResults() > 0) { locallyScopedConn.execSQL(this, "SET net_write_timeout=" + this.connection.getNetTimeoutForStreamingResults(), -1, null, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, false, this.currentCatalog, null, false); } Buffer sendPacket = fillSendPacket(); if (this.results != null) { if (!this.connection.getHoldResultsOpenOverStatementClose()) { if (!this.holdResultsOpenOverClose) { this.results.realClose(false); } } } String oldCatalog = null; if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) { oldCatalog = locallyScopedConn.getCatalog(); locallyScopedConn.setCatalog(this.currentCatalog); } // // Check if we have cached metadata for this query... // if (locallyScopedConn.getCacheResultSetMetadata()) { cachedMetadata = locallyScopedConn.getCachedMetaData(this.originalSql); } Field[] metadataFromCache = null; if (cachedMetadata != null) { metadataFromCache = cachedMetadata.fields; } if (locallyScopedConn.useMaxRows()) { // 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). if (this.hasLimitClause) { this.results = executeInternal(this.maxRows, sendPacket, createStreamingResultSet(), true, metadataFromCache, false); } else { if (this.maxRows <= 0) { executeSimpleNonQuery(locallyScopedConn, "SET OPTION SQL_SELECT_LIMIT=DEFAULT"); } else { executeSimpleNonQuery(locallyScopedConn, "SET OPTION SQL_SELECT_LIMIT=" + this.maxRows); } this.results = executeInternal(-1, sendPacket, doStreaming, true, metadataFromCache, false); if (oldCatalog != null) { this.connection.setCatalog(oldCatalog); } } } else { this.results = executeInternal(-1, sendPacket, doStreaming, true, metadataFromCache, false); } if (oldCatalog != null) { locallyScopedConn.setCatalog(oldCatalog); } if (cachedMetadata != null) { locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql, cachedMetadata, this.results); } else { if (locallyScopedConn.getCacheResultSetMetadata()) { locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql, null /* will be created */, this.results); } } } this.lastInsertId = this.results.getUpdateID(); return this.results; } /** * Execute a SQL INSERT, UPDATE or DELETE statement. In addition, SQL * statements that return nothing such as SQL DDL statements can be * executed. * * @return either the row count for INSERT, UPDATE or DELETE; or 0 for SQL * statements that return nothing. * * @exception SQLException * if a database access error occurs */ public int executeUpdate() throws SQLException { return executeUpdate(true, false); } /* * We need this variant, because ServerPreparedStatement calls this for * batched updates, which will end up clobbering the warnings and generated * keys we need to gather for the batch. */ protected int executeUpdate( boolean clearBatchedGeneratedKeysAndWarnings, boolean isBatch) throws SQLException { if (clearBatchedGeneratedKeysAndWarnings) { clearWarnings(); this.batchedGeneratedKeys = null; } return executeUpdate(this.parameterValues, this.parameterStreams, this.isStream, this.streamLengths, this.isNull, isBatch); } /** * Added to allow batch-updates * * @param batchedParameterStrings * string values used in single statement * @param batchedParameterStreams * stream values used in single statement * @param batchedIsStream * flags for streams used in single statement * @param batchedStreamLengths * lengths of streams to be read. * @param batchedIsNull * flags for parameters that are null * * @return the update count * * @throws SQLException * if a database error occurs */ protected int executeUpdate(byte[][] batchedParameterStrings, InputStream[] batchedParameterStreams, boolean[] batchedIsStream, int[] batchedStreamLengths, boolean[] batchedIsNull, boolean isReallyBatch) throws SQLException { checkClosed(); ConnectionImpl locallyScopedConn = this.connection; if (locallyScopedConn.isReadOnly()) { throw SQLError.createSQLException(Messages.getString("PreparedStatement.34") //$NON-NLS-1$ + Messages.getString("PreparedStatement.35"), //$NON-NLS-1$ SQLError.SQL_STATE_ILLEGAL_ARGUMENT); } if ((this.firstCharOfStmt == 'S') && isSelectQuery()) { //$NON-NLS-1$ throw SQLError.createSQLException(Messages.getString("PreparedStatement.37"), //$NON-NLS-1$ "01S03"); //$NON-NLS-1$ } if (this.results != null) { if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) { this.results.realClose(false); } } ResultSetInternalMethods rs = null; // The checking and changing of catalogs // must happen in sequence, so synchronize // on the same mutex that _conn is using synchronized (locallyScopedConn.getMutex()) { Buffer sendPacket = fillSendPacket(batchedParameterStrings, batchedParameterStreams, batchedIsStream, batchedStreamLengths); String oldCatalog = null; if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) { oldCatalog = locallyScopedConn.getCatalog(); locallyScopedConn.setCatalog(this.currentCatalog); } // // Only apply max_rows to selects // if (locallyScopedConn.useMaxRows()) { executeSimpleNonQuery(locallyScopedConn, "SET OPTION SQL_SELECT_LIMIT=DEFAULT"); } boolean oldInfoMsgState = false; if (this.retrieveGeneratedKeys) { oldInfoMsgState = locallyScopedConn.isReadInfoMsgEnabled(); locallyScopedConn.setReadInfoMsgEnabled(true); } rs = executeInternal(-1, sendPacket, false, false, null, isReallyBatch); if (this.retrieveGeneratedKeys) { locallyScopedConn.setReadInfoMsgEnabled(oldInfoMsgState); rs.setFirstCharOfQuery(this.firstCharOfStmt); } if (oldCatalog != null) { locallyScopedConn.setCatalog(oldCatalog); } } this.results = rs; this.updateCount = rs.getUpdateCount(); if (containsOnDuplicateKeyUpdateInSQL() && this.compensateForOnDuplicateKeyUpdate) { if (this.updateCount == 2 || this.updateCount == 0) { this.updateCount = 1; } } int truncatedUpdateCount = 0; if (this.updateCount > Integer.MAX_VALUE) { truncatedUpdateCount = Integer.MAX_VALUE; } else { truncatedUpdateCount = (int) this.updateCount; } this.lastInsertId = rs.getUpdateID(); return truncatedUpdateCount; } protected boolean containsOnDuplicateKeyUpdateInSQL() { return this.parseInfo.isOnDuplicateKeyUpdate; } private String extractValuesClause() throws SQLException { if (this.batchedValuesClause == null) { String quoteCharStr = this.connection.getMetaData() .getIdentifierQuoteString(); int indexOfValues = -1; if (quoteCharStr.length() > 0) { indexOfValues = StringUtils.indexOfIgnoreCaseRespectQuotes( this.statementAfterCommentsPos, this.originalSql, "VALUES ", quoteCharStr.charAt(0), false); } else { indexOfValues = StringUtils.indexOfIgnoreCase(this.statementAfterCommentsPos, this.originalSql, "VALUES "); } if (indexOfValues == -1) { return null; } int indexOfFirstParen = this.originalSql .indexOf('(', indexOfValues + 7); if (indexOfFirstParen == -1) { return null; } int indexOfLastParen = this.originalSql.lastIndexOf(')'); if (indexOfLastParen == -1) { return null; } this.batchedValuesClause = this.originalSql.substring(indexOfFirstParen, indexOfLastParen + 1); } return this.batchedValuesClause; } /** * Creates the packet that contains the query to be sent to the server. * * @return A Buffer filled with the query representing the * PreparedStatement. * * @throws SQLException * if an error occurs. */ protected Buffer fillSendPacket() throws SQLException { return fillSendPacket(this.parameterValues, this.parameterStreams, this.isStream, this.streamLengths); } /** * Creates the packet that contains the query to be sent to the server. * * @param batchedParameterStrings * the parameters as strings * @param batchedParameterStreams * the parameters as streams * @param batchedIsStream * is the given parameter a stream? * @param batchedStreamLengths * the lengths of the streams (if appropriate) * * @return a Buffer filled with the query that represents this statement * * @throws SQLException * if an error occurs. */ protected Buffer fillSendPacket(byte[][] batchedParameterStrings, InputStream[] batchedParameterStreams, boolean[] batchedIsStream, int[] batchedStreamLengths) throws SQLException { Buffer sendPacket = this.connection.getIO().getSharedSendPacket(); sendPacket.clear(); sendPacket.writeByte((byte) MysqlDefs.QUERY); boolean useStreamLengths = this.connection .getUseStreamLengthsInPrepStmts(); // // Try and get this allocation as close as possible // for BLOBs // int ensurePacketSize = 0; String statementComment = this.connection.getStatementComment(); byte[] commentAsBytes = null; if (statementComment != null) { if (this.charConverter != null) { commentAsBytes = this.charConverter.toBytes(statementComment); } else { commentAsBytes = StringUtils.getBytes(statementComment, this.charConverter, this.charEncoding, this.connection .getServerCharacterEncoding(), this.connection .parserKnowsUnicode()); } ensurePacketSize += commentAsBytes.length; ensurePacketSize += 6; // for /*[space] [space]*/ } for (int i = 0; i < batchedParameterStrings.length; i++) { if (batchedIsStream[i] && useStreamLengths) { ensurePacketSize += batchedStreamLengths[i]; } } if (ensurePacketSize != 0) { sendPacket.ensureCapacity(ensurePacketSize); } if (commentAsBytes != null) { sendPacket.writeBytesNoNull(Constants.SLASH_STAR_SPACE_AS_BYTES); sendPacket.writeBytesNoNull(commentAsBytes); sendPacket.writeBytesNoNull(Constants.SPACE_STAR_SLASH_SPACE_AS_BYTES); } for (int i = 0; i < batchedParameterStrings.length; i++) { if ((batchedParameterStrings[i] == null) && (batchedParameterStreams[i] == null)) { throw SQLError.createSQLException(Messages .getString("PreparedStatement.40") //$NON-NLS-1$ + (i + 1), SQLError.SQL_STATE_WRONG_NO_OF_PARAMETERS); } sendPacket.writeBytesNoNull(this.staticSqlStrings[i]); if (batchedIsStream[i]) { streamToBytes(sendPacket, batchedParameterStreams[i], true, batchedStreamLengths[i], useStreamLengths); } else { sendPacket.writeBytesNoNull(batchedParameterStrings[i]); } } sendPacket .writeBytesNoNull(this.staticSqlStrings[batchedParameterStrings.length]); return sendPacket; } private String generateBatchedInsertSQL(String valuesClause, int numBatches) { StringBuffer newStatementSql = new StringBuffer(this.originalSql .length() + (numBatches * (valuesClause.length() + 1))); newStatementSql.append(this.originalSql); for (int i = 0; i < numBatches - 1; i++) { newStatementSql.append(','); newStatementSql.append(valuesClause); } return newStatementSql.toString(); } /** * DOCUMENT ME! * * @param parameterIndex * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws SQLException * DOCUMENT ME! */ public byte[] getBytesRepresentation(int parameterIndex) throws SQLException { if (this.isStream[parameterIndex]) { return streamToBytes(this.parameterStreams[parameterIndex], false, this.streamLengths[parameterIndex], this.connection .getUseStreamLengthsInPrepStmts()); } byte[] parameterVal = this.parameterValues[parameterIndex]; if (parameterVal == null) { return null; } if ((parameterVal[0] == '\'') && (parameterVal[parameterVal.length - 1] == '\'')) { byte[] valNoQuotes = new byte[parameterVal.length - 2]; System.arraycopy(parameterVal, 1, valNoQuotes, 0, parameterVal.length - 2); return valNoQuotes; } return parameterVal; } // --------------------------JDBC 2.0----------------------------- private final String getDateTimePattern(String dt, boolean toTime) throws Exception { // // Special case // int dtLength = (dt != null) ? dt.length() : 0; if ((dtLength >= 8) && (dtLength <= 10)) { int dashCount = 0; boolean isDateOnly = true; for (int i = 0; i < dtLength; i++) { char c = dt.charAt(i); if (!Character.isDigit(c) && (c != '-')) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -