preparedstatement.java

来自「mysql的jdbc驱动」· Java 代码 · 共 2,423 行 · 第 1/5 页

JAVA
2,423
字号
				}			}			String oldCatalog = null;			if (!this.connection.getCatalog().equals(this.currentCatalog)) {				oldCatalog = this.connection.getCatalog();				this.connection.setCatalog(this.currentCatalog);			}			//			// Check if we have cached metadata for this query...			//			if (this.connection.getCacheResultSetMetadata()) {				cachedMetadata = getCachedMetaData(this.originalSql);			}			if (this.connection.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,							(cachedMetadata == null));				} else {					if (this.maxRows <= 0) {						this.connection								.execSQL(										this,										"SET OPTION SQL_SELECT_LIMIT=DEFAULT", -1, null, //$NON-NLS-1$										java.sql.ResultSet.TYPE_FORWARD_ONLY,										java.sql.ResultSet.CONCUR_READ_ONLY,										false, false, this.currentCatalog, true);					} else {						this.connection								.execSQL(										this,										"SET OPTION SQL_SELECT_LIMIT=" + this.maxRows, -1, null, //$NON-NLS-1$										java.sql.ResultSet.TYPE_FORWARD_ONLY,										java.sql.ResultSet.CONCUR_READ_ONLY,										false, false, this.currentCatalog, true);					}					this.results = executeInternal(-1, sendPacket,							createStreamingResultSet(), true,							(cachedMetadata == null));					if (oldCatalog != null) {						this.connection.setCatalog(oldCatalog);					}				}			} else {				this.results = executeInternal(-1, sendPacket,						createStreamingResultSet(), true,						(cachedMetadata == null));			}			if (oldCatalog != null) {				this.connection.setCatalog(oldCatalog);			}		}		this.lastInsertId = this.results.getUpdateID();		if (cachedMetadata != null) {			initializeResultsMetadataFromCache(this.originalSql,					cachedMetadata, this.results);		} else {			if (this.connection.getCacheResultSetMetadata()) {				initializeResultsMetadataFromCache(this.originalSql,						null /* will be created */, this.results);			}		}		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 synchronized int executeUpdate() throws SQLException {		return executeUpdate(true);	}	/*	 * 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 synchronized int executeUpdate(			boolean clearBatchedGeneratedKeysAndWarnings) throws SQLException {		if (clearBatchedGeneratedKeysAndWarnings) {			clearWarnings();			this.batchedGeneratedKeys = null;		}		return executeUpdate(this.parameterValues, this.parameterStreams,				this.isStream, this.streamLengths, this.isNull);	}	/**	 * 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 synchronized int executeUpdate(byte[][] batchedParameterStrings,			InputStream[] batchedParameterStreams, boolean[] batchedIsStream,			int[] batchedStreamLengths, boolean[] batchedIsNull)			throws SQLException {		if (this.connection.isReadOnly()) {			throw new SQLException(Messages.getString("PreparedStatement.34") //$NON-NLS-1$					+ Messages.getString("PreparedStatement.35"), //$NON-NLS-1$					SQLError.SQL_STATE_ILLEGAL_ARGUMENT);		}		checkClosed();		if ((this.firstCharOfStmt == 'S')				&& StringUtils.startsWithIgnoreCaseAndWs(this.originalSql,						"SELECT")) { //$NON-NLS-1$			throw new SQLException(Messages.getString("PreparedStatement.37"), //$NON-NLS-1$					"01S03"); //$NON-NLS-1$		}		if (this.results != null) {			if (!this.connection.getHoldResultsOpenOverStatementClose()) {				this.results.realClose(false);			}		}		ResultSet rs = null;		// The checking and changing of catalogs		// must happen in sequence, so synchronize		// on the same mutex that _conn is using		synchronized (this.connection.getMutex()) {			Buffer sendPacket = fillSendPacket(batchedParameterStrings,					batchedParameterStreams, batchedIsStream,					batchedStreamLengths);			String oldCatalog = null;			if (!this.connection.getCatalog().equals(this.currentCatalog)) {				oldCatalog = this.connection.getCatalog();				this.connection.setCatalog(this.currentCatalog);			}			//			// Only apply max_rows to selects			//			if (this.connection.useMaxRows()) {				this.connection.execSQL(this,						"SET OPTION SQL_SELECT_LIMIT=DEFAULT", -1, null, //$NON-NLS-1$						java.sql.ResultSet.TYPE_FORWARD_ONLY,						java.sql.ResultSet.CONCUR_READ_ONLY, false, false,						this.currentCatalog, true);			}			boolean oldInfoMsgState = false;			if (this.retrieveGeneratedKeys) {				oldInfoMsgState = this.connection.isReadInfoMsgEnabled();				this.connection.setReadInfoMsgEnabled(true);			}			rs = executeInternal(-1, sendPacket, false, false, true);			if (this.retrieveGeneratedKeys) {				this.connection.setReadInfoMsgEnabled(oldInfoMsgState);				rs.setFirstCharOfQuery(this.firstCharOfStmt);			}			if (oldCatalog != null) {				this.connection.setCatalog(oldCatalog);			}		}		this.results = rs;		this.updateCount = rs.getUpdateCount();		int truncatedUpdateCount = 0;		if (this.updateCount > Integer.MAX_VALUE) {			truncatedUpdateCount = Integer.MAX_VALUE;		} else {			truncatedUpdateCount = (int) this.updateCount;		}		this.lastInsertId = rs.getUpdateID();		return truncatedUpdateCount;	}	/**	 * 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;		for (int i = 0; i < batchedParameterStrings.length; i++) {			if (batchedIsStream[i] && useStreamLengths) {				ensurePacketSize += batchedStreamLengths[i];			}		}		if (ensurePacketSize != 0) {			sendPacket.ensureCapacity(ensurePacketSize);		}		for (int i = 0; i < batchedParameterStrings.length; i++) {			if ((batchedParameterStrings[i] == null)					&& (batchedParameterStreams[i] == null)) {				throw new SQLException(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;	}	/**	 * 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 != '-')) {					isDateOnly = false;					break;				}				if (c == '-') {					dashCount++;				}			}			if (isDateOnly && (dashCount == 2)) {				return "yyyy-MM-dd"; //$NON-NLS-1$			}		}		//		// Special case - time-only		//		boolean colonsOnly = true;		for (int i = 0; i < dtLength; i++) {			char c = dt.charAt(i);			if (!Character.isDigit(c) && (c != ':')) {				colonsOnly = false;				break;			}		}		if (colonsOnly) {			return "HH:mm:ss"; //$NON-NLS-1$		}		int n;		int z;		int count;		int maxvecs;		char c;		char separator;		StringReader reader = new StringReader(dt + " "); //$NON-NLS-1$		ArrayList vec = new ArrayList();		ArrayList vecRemovelist = new ArrayList();		Object[] nv = new Object[3];		Object[] v;		nv[0] = new Character('y');		nv[1] = new StringBuffer();		nv[2] = new Integer(0);		vec.add(nv);		if (toTime) {			nv = new Object[3];			nv[0] = new Character('h');			nv[1] = new StringBuffer();			nv[2] = new Integer(0);			vec.add(nv);		}		while ((z = reader.read()) != -1) {			separator = (char) z;			maxvecs = vec.size();			for (count = 0; count < maxvecs; count++) {				v = (Object[]) vec.get(count);				n = ((Integer) v[2]).intValue();				c = getSuccessor(((Character) v[0]).charValue(), n);				if (!Character.isLetterOrDigit(separator)) {					if ((c == ((Character) v[0]).charValue()) && (c != 'S')) {						vecRemovelist.add(v);					} else {						((StringBuffer) v[1]).append(separator);						if ((c == 'X') || (c == 'Y')) {							v[2] = new Integer(4);						}					}				} else {					if (c == 'X') {						c = 'y';						nv = new Object[3];						nv[1] = (new StringBuffer(((StringBuffer) v[1])								.toString())).append('M');						nv[0] = new Character('M');						nv[2] = new Integer(1);						vec.add(nv);					} else if (c == 'Y') {						c = 'M';						nv = new Object[3];						nv[1] = (new StringBuffer(((StringBuffer) v[1])								.toString())).append('d');						nv[0] = new Character('d');						nv[2] = new Integer(1);						vec.add(nv);					}					((StringBuffer) v[1]).append(c);					if (c == ((Character) v[0]).charValue()) {						v[2] = new Integer(n + 1);					} else {						v[0] = new Character(c);						v[2] = new Integer(1);					}				}			}			int size = vecRemovelist.size();			for (int i = 0; i < size; i++) {				v = (Object[]) vecRemovelist.get(i);				vec.remove(v);			}			vecRemovelist.clear();		}		int size = vec.size();		for (int i = 0; i < size; i++) {			v = (Object[]) vec.get(i);			c = ((Character) v[0]).charValue();			n = ((Integer) v[2]).intValue();			boolean bk = getSuccessor(c, n) != c;			boolean atEnd = (((c == 's') || (c == 'm') || ((c == 'h') && toTime)) && bk);			boolean finishesAtDate = (bk && (c == 'd') && !toTime);			boolean containsEnd = (((StringBuffer) v[1]).toString()

⌨️ 快捷键说明

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