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

📄 statement.java

📁 开发MySql数据库的最新JDBC驱动。
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
							if (this.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 {				this.retrieveGeneratedKeys = false;								clearBatch();			}		}	}	/**	 * Rewrites batch into a single query to send to the server. This method	 * will constrain each batch to be shorter than max_allowed_packet on the	 * server.	 * 	 * @return update counts in the same manner as executeBatch()	 * @throws SQLException	 */	private int[] executeBatchUsingMultiQueries(boolean multiQueriesEnabled,			int nbrCommands) throws SQLException {		Connection locallyScopedConn = this.connection;				if (!multiQueriesEnabled) {			locallyScopedConn.getIO().enableMultiQueries();		}		java.sql.Statement batchStmt = null;				try {			int[] updateCounts = new int[nbrCommands];			for (int i = 0; i < nbrCommands; i++) {				updateCounts[i] = -3;			}			int commandIndex = 0;			StringBuffer queryBuf = new StringBuffer();									batchStmt = locallyScopedConn.createStatement();						int counter = 0;			int numberOfBytesPerChar = 1;			String connectionEncoding = locallyScopedConn.getEncoding();			if (StringUtils.startsWithIgnoreCase(connectionEncoding, "utf")) {				numberOfBytesPerChar = 3;			} else if (CharsetMapping.isMultibyteCharset(connectionEncoding)) {				numberOfBytesPerChar = 2;			}			int escapeAdjust = 1;						if (this.doEscapeProcessing) {				escapeAdjust = 2; /* We assume packet _could_ grow by this amount, as we're not				                     sure how big statement will end up after				                     escape processing */			}						for (commandIndex = 0; commandIndex < nbrCommands; commandIndex++) {				String nextQuery = (String) this.batchedArgs.get(commandIndex);				if (((((queryBuf.length() + nextQuery.length())						* numberOfBytesPerChar) + 1 /* for semicolon */ 						+ MysqlIO.HEADER_LENGTH) * escapeAdjust)  + 32 > this.connection						.getMaxAllowedPacket()) {					batchStmt.execute(queryBuf.toString());					updateCounts[counter++] = batchStmt.getUpdateCount();					long generatedKeyStart = ((com.mysql.jdbc.Statement)batchStmt).getLastInsertID();					byte[][] row = new byte[1][];					row[0] = Long.toString(generatedKeyStart++).getBytes();					this.batchedGeneratedKeys.add(row);					while (batchStmt.getMoreResults()							|| batchStmt.getUpdateCount() != -1) {						updateCounts[counter++] = batchStmt.getUpdateCount();						row = new byte[1][];						row[0] = Long.toString(generatedKeyStart++).getBytes();						this.batchedGeneratedKeys.add(row);					}					queryBuf = new StringBuffer();				}				queryBuf.append(nextQuery);				queryBuf.append(";");			}			if (queryBuf.length() > 0) {				batchStmt.execute(queryBuf.toString());				long generatedKeyStart = ((com.mysql.jdbc.Statement)batchStmt).getLastInsertID();				byte[][] row = new byte[1][];				row[0] = Long.toString(generatedKeyStart++).getBytes();				this.batchedGeneratedKeys.add(row);								updateCounts[counter++] = batchStmt.getUpdateCount();				while (batchStmt.getMoreResults()						|| batchStmt.getUpdateCount() != -1) {					updateCounts[counter++] = batchStmt.getUpdateCount();					row = new byte[1][];					row[0] = Long.toString(generatedKeyStart++).getBytes();					this.batchedGeneratedKeys.add(row);				}			}			return (updateCounts != null) ? updateCounts : new int[0];		} finally {			try {				if (batchStmt != null) {					batchStmt.close();				}			} finally {				if (!multiQueriesEnabled) {					locallyScopedConn.getIO().disableMultiQueries();				}			}		}	}		/**	 * Execute a SQL statement that retruns a single ResultSet	 * 	 * @param sql	 *            typically a static SQL SELECT statement	 * 	 * @return a ResulSet that contains the data produced by the query	 * 	 * @exception SQLException	 *                if a database access error occurs	 */	public java.sql.ResultSet executeQuery(String sql)			throws SQLException {		checkClosed();				Connection locallyScopedConn = this.connection;				synchronized (locallyScopedConn.getMutex()) {			synchronized (this.cancelTimeoutMutex) {				this.wasCancelled = false;			}				checkNullOrEmptyQuery(sql);			if (this.doEscapeProcessing) {				Object escapedSqlResult = EscapeProcessor.escapeSQL(sql,						locallyScopedConn.serverSupportsConvertFn(), this.connection);					if (escapedSqlResult instanceof String) {					sql = (String) escapedSqlResult;				} else {					sql = ((EscapeProcessorResult) escapedSqlResult).escapedSql;				}			}				char firstStatementChar = StringUtils.firstNonWsCharUc(sql, 					findStartOfStatement(sql));				checkForDml(sql, firstStatementChar);				if (this.results != null) {				if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) {					this.results.realClose(false);				}			}				CachedResultSetMetaData cachedMetaData = null;				// 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 (useServerFetch()) {				this.results = createResultSetUsingServerFetch(sql);				return this.results;			}			CancelTask timeoutTask = null;						String oldCatalog = null;						try {				if (locallyScopedConn.getEnableQueryTimeouts() &&						this.timeoutInMillis != 0						&& locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {					timeoutTask = new CancelTask();					Connection.getCancelTimer().schedule(timeoutTask, 							this.timeoutInMillis);				}				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(sql);				}				if (locallyScopedConn.useMaxRows()) {					// We need to execute this all together					// So synchronize on the Connection's mutex (because					// even queries going through there synchronize					// on the connection					if (StringUtils.indexOfIgnoreCase(sql, "LIMIT") != -1) { //$NON-NLS-1$						this.results = locallyScopedConn.execSQL(this, sql,								this.maxRows, null, this.resultSetType,								this.resultSetConcurrency,								createStreamingResultSet(),								this.currentCatalog, (cachedMetaData == null));					} else {						if (this.maxRows <= 0) {							locallyScopedConn									.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, this.currentCatalog,											true); //$NON-NLS-1$						} else {							locallyScopedConn									.execSQL(											this,											"SET OPTION SQL_SELECT_LIMIT=" + this.maxRows, -1, //$NON-NLS-1$											null,											java.sql.ResultSet.TYPE_FORWARD_ONLY,											java.sql.ResultSet.CONCUR_READ_ONLY,											false, this.currentCatalog,											true); //$NON-NLS-1$						}						this.results = locallyScopedConn.execSQL(this, sql, -1,								null, this.resultSetType,								this.resultSetConcurrency,								createStreamingResultSet(),								this.currentCatalog, (cachedMetaData == null));						if (oldCatalog != null) {							locallyScopedConn.setCatalog(oldCatalog);						}					}				} else {					this.results = locallyScopedConn.execSQL(this, sql, -1, null,							this.resultSetType, this.resultSetConcurrency,							createStreamingResultSet(),							this.currentCatalog, (cachedMetaData == null));				}				if (timeoutTask != null) {					if (timeoutTask.caughtWhileCancelling != null) {						throw timeoutTask.caughtWhileCancelling;					}										timeoutTask.cancel();					timeoutTask = null;				}								synchronized (this.cancelTimeoutMutex) {					if (this.wasCancelled) {						this.wasCancelled = false;						throw new MySQLTimeoutException();					}				}			} finally {				if (timeoutTask != null) {					timeoutTask.cancel();				}								if (oldCatalog != null) {					locallyScopedConn.setCatalog(oldCatalog);				}			}			this.lastInsertId = this.results.getUpdateID();			if (cachedMetaData != null) {				locallyScopedConn.initializeResultsMetadataFromCache(sql, cachedMetaData,						this.results);			} else {				if (this.connection.getCacheResultSetMetadata()) {					locallyScopedConn.initializeResultsMetadataFromCache(sql,							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	 * Any IDs generated for AUTO_INCREMENT fields can be retrieved by casting	 * this Statement to org.gjt.mm.mysql.Statement and calling the	 * getLastInsertID() method.	 * 	 * @param sql	 *            a SQL statement	 * 	 * @return either a row count, or 0 for SQL commands	 * 	 * @exception SQLException	 *                if a database access error occurs	 */	public int executeUpdate(String sql) throws SQLException {		return executeUpdate(sql, false);	}	protected int executeUpdate(String sql, boolean isBatch)			throws SQLException {		checkClosed();				Connection locallyScopedConn = this.connection;				char firstStatementChar = StringUtils.firstNonWsCharUc(sql,				findStartOfStatement(sql));		ResultSet rs = null;		synchronized (locallyScopedConn.getMutex()) {			synchronized (this.cancelTimeoutMutex) {				this.wasCancelled = false;			}				checkNullOrEmptyQuery(sql);			if (this.doEscapeProcessing) {				Object escapedSqlResult = EscapeProcessor.escapeSQL(sql,						this.connection.serverSupportsConvertFn(), this.connection);				if (escapedSqlResult instanceof String) {					sql = (String) escapedSqlResult;				} else {					sql = ((EscapeProcessorResult) escapedSqlResult).escapedSql;				}			}						if (locallyScopedConn.isReadOnly()) {				throw SQLError.createSQLException(Messages						.getString("Statement.42") //$NON-NLS-1$						+ Messages.getString("Statement.43"), //$NON-NLS-1$						SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$			}				if (StringUtils.startsWithIgnoreCaseAndWs(sql, "select")) { //$NON-NLS-1$				throw SQLError.createSQLException(Messages						.getString("Statement.46"), //$NON-NLS-1$						"01S03"); //$NON-NLS-1$			}				if (this.results != null) {				if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) {					this.results.realClose(false);				}			}				// The checking and changing of catalogs			// must happen in sequence, so synchronize			// on the same mutex that _conn is using					CancelTask timeoutTask = null;						String oldCatalog = null;						try {				if (locallyScopedConn.getEnableQueryTimeouts() &&						this.timeoutInMillis != 0						&& locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {					timeoutTask = new CancelTask();					Connection.getCancelTimer().schedule(timeoutTask, 							this.timeoutInMillis);				}				if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) {					oldCatalog = locallyScopedConn.getCatalog();					locallyScopedConn.setCatalog(this.currentCatalog);				}				//				// Only apply max_rows to selects				//				if (locallyScopedConn.useMaxRows()) {					locallyScopedConn.execSQL(							this,							"SET OPTION SQL_SELECT_LIMIT=DEFAULT", //$NON-NLS-1$							-1, null, java.sql.ResultSet.TYPE_FORWARD_ONLY,							java.sql.ResultSet.CONCUR_READ_ONLY, false,							this.currentCatalog, true);				}				rs = locallyScopedConn.execSQL(this, sql, -1, null,						java.sql.ResultSet.TYPE_FORWARD_ONLY,						java.sql.ResultSet.CONCUR_READ_ONLY, false,						this.currentCatalog,						true /* force read of field info on DML */,						isBatch);								if (timeoutTask != null) {					if (timeoutTask.caughtWhileCancelling != null) {						throw timeoutTask.caughtWhileCancelling;					}										timeoutTask.cancel();					timeoutTask = null;				}				synchronized (this.cancelTimeoutMutex) {					if (this.wasCancelled) {						this.wasCancelled = false;						throw new MySQLTimeoutException();					}				}			} finally {				if (timeoutTask != null) {					timeoutTask.cancel();				}								if (oldCatalog != null) {					locallyScopedConn.setCatalog(oldCatalog);				}			}		}		this.results = rs;		rs.setFirstCharOfQuery(firstStatementChar);		this.updateCount = rs.getUpdateCount();

⌨️ 快捷键说明

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