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

📄 statement.java

📁 mysql的jdbc驱动
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/* Copyright (C) 2002-2004 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as  published by the Free Software Foundation. There are special exceptions to the terms and conditions of the GPL  as it is applied to this software. View the full text of the  exception in file EXCEPTIONS-CONNECTOR-J in the directory of this  software distribution. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */package com.mysql.jdbc;import com.mysql.jdbc.profiler.ProfileEventSink;import com.mysql.jdbc.profiler.ProfilerEvent;import com.mysql.jdbc.util.LRUCache;import java.sql.DataTruncation;import java.sql.SQLException;import java.sql.SQLWarning;import java.sql.Types;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Locale;import java.util.Map;/** * A Statement object is used for executing a static SQL statement and obtaining * the results produced by it. *  * <p> * Only one ResultSet per Statement can be open at any point in time. Therefore, * if the reading of one ResultSet is interleaved with the reading of another, * each must have been generated by different Statements. All statement execute * methods implicitly close a statement's current ResultSet if an open one * exists. * </p> *  * @author Mark Matthews * @version $Id: Statement.java 4265 2005-09-16 20:00:17Z mmatthews $ *  * @see java.sql.Statement * @see ResultSet */public class Statement implements java.sql.Statement {	class CachedResultSetMetaData {		/** Map column names (and all of their permutations) to column indices */		Map columnNameToIndex = null;		/** Cached Field info */		Field[] fields;		/** Map of fully-specified column names to column indices */		Map fullColumnNameToIndex = null;		/** Cached ResultSetMetaData */		java.sql.ResultSetMetaData metadata;	}	/** Used to generate IDs when profiling. */	protected static int statementCounter = 1;	public final static byte USES_VARIABLES_FALSE = 0;	public final static byte USES_VARIABLES_TRUE = 1;	public final static byte USES_VARIABLES_UNKNOWN = -1;	/** Holds batched commands */	protected List batchedArgs;	/** The character converter to use (if available) */	protected SingleByteCharsetConverter charConverter = null;	/** The character encoding to use (if available) */	protected String charEncoding = null;	/** The connection that created us */	protected Connection connection = null;	/** The catalog in use */	protected String currentCatalog = null;	/** Should we process escape codes? */	protected boolean doEscapeProcessing = true;	/** If we're profiling, where should events go to? */	protected ProfileEventSink eventSink = null;	/** The number of rows to fetch at a time (currently ignored) */	private int fetchSize = 0;	/** Has this statement been closed? */	protected boolean isClosed = false;	/** The auto_increment value for the last insert */	protected long lastInsertId = -1;	/** The max field size for this statement */	protected int maxFieldSize = MysqlIO.getMaxBuf();	/**	 * The maximum number of rows to return for this statement (-1 means _all_	 * rows)	 */	protected int maxRows = -1;	/** Has someone changed this for this statement? */	protected boolean maxRowsChanged = false;	/** List of currently-open ResultSets */	protected List openResults = new ArrayList();	/** Are we in pedantic mode? */	protected boolean pedantic = false;	/**	 * Where this statement was created, only used if profileSql or	 * useUsageAdvisor set to true.	 */	protected Throwable pointOfOrigin;	/** Should we profile? */	protected boolean profileSQL = false;	/** The current results */	protected ResultSet results = null;	/** The concurrency for this result set (updatable or not) */	protected int resultSetConcurrency = 0;	/** Cache of ResultSet metadata */	protected LRUCache resultSetMetadataCache;	/** The type of this result set (scroll sensitive or in-sensitive) */	protected int resultSetType = 0;	/** Used to identify this statement when profiling. */	protected int statementId;	/** The timeout for a query */	protected int timeout = 0;	/** The update count for this statement */	protected long updateCount = -1;	/** Should we use the usage advisor? */	protected boolean useUsageAdvisor = false;	/** The warnings chain. */	protected SQLWarning warningChain = null;	/**	 * Constructor for a Statement.	 * 	 * @param c	 *            the Connection instantation that creates us	 * @param catalog	 *            the database name in use when we were created	 * 	 * @throws SQLException	 *             if an error occurs.	 */	public Statement(Connection c, String catalog) throws SQLException {		if ((c == null) || c.isClosed()) {			throw new SQLException(Messages.getString("Statement.0"), //$NON-NLS-1$					SQLError.SQL_STATE_CONNECTION_NOT_OPEN); //$NON-NLS-1$ //$NON-NLS-2$		}		this.connection = c;		this.currentCatalog = catalog;		this.pedantic = this.connection.getPedantic();		if (!this.connection.getDontTrackOpenResources()) {			this.connection.registerStatement(this);		}		//		// Adjust, if we know it		//		if (this.connection != null) {			this.maxFieldSize = this.connection.getMaxAllowedPacket();		}		if (this.connection.getUseUnicode()) {			this.charEncoding = this.connection.getEncoding();			this.charConverter = this.connection					.getCharsetConverter(this.charEncoding);		}		boolean profiling = this.connection.getProfileSql()				|| this.connection.getUseUsageAdvisor();		if (this.connection.getAutoGenerateTestcaseScript() || profiling) {			this.statementId = statementCounter++;		}		if (profiling) {			this.pointOfOrigin = new Throwable();			this.profileSQL = this.connection.getProfileSql();			this.useUsageAdvisor = this.connection.getUseUsageAdvisor();			this.eventSink = ProfileEventSink.getInstance(this.connection);		}		int maxRowsConn = this.connection.getMaxRows();		if (maxRowsConn != -1) {			setMaxRows(maxRowsConn);		}	}	/**	 * DOCUMENT ME!	 * 	 * @param sql	 *            DOCUMENT ME!	 * 	 * @throws SQLException	 *             DOCUMENT ME!	 */	public synchronized void addBatch(String sql) throws SQLException {		if (this.batchedArgs == null) {			this.batchedArgs = new ArrayList();		}		if (sql != null) {			this.batchedArgs.add(sql);		}	}	/**	 * Cancel can be used by one thread to cancel a statement that is being	 * executed by another thread. However this driver is synchronous, so this	 * really has no meaning - we define it as a no-op (i.e. you can't cancel,	 * but there is no error if you try.)	 * 	 * @exception SQLException	 *                only because thats the spec.	 */	public void cancel() throws SQLException {		// No-op	}	// --------------------------JDBC 2.0-----------------------------	/**	 * Checks if closed() has been called, and throws an exception if so	 * 	 * @throws SQLException	 *             if this statement has been closed	 */	protected void checkClosed() throws SQLException {		if (this.isClosed) {			throw new SQLException(Messages.getString("Statement.49"), //$NON-NLS-1$					SQLError.SQL_STATE_CONNECTION_NOT_OPEN); //$NON-NLS-1$		}	}	/**	 * Checks if the given SQL query with the given first non-ws char is a DML	 * statement. Throws an exception if it is.	 * 	 * @param sql	 *            the SQL to check	 * @param firstStatementChar	 *            the UC first non-ws char of the statement	 * 	 * @throws SQLException	 *             if the statement contains DML	 */	protected void checkForDml(String sql, char firstStatementChar)			throws SQLException {		if ((firstStatementChar == 'I') || (firstStatementChar == 'U')				|| (firstStatementChar == 'D') || (firstStatementChar == 'A')				|| (firstStatementChar == 'C')) {			if (StringUtils.startsWithIgnoreCaseAndWs(sql, "INSERT") //$NON-NLS-1$					|| StringUtils.startsWithIgnoreCaseAndWs(sql, "UPDATE") //$NON-NLS-1$					|| StringUtils.startsWithIgnoreCaseAndWs(sql, "DELETE") //$NON-NLS-1$					|| StringUtils.startsWithIgnoreCaseAndWs(sql, "DROP") //$NON-NLS-1$					|| StringUtils.startsWithIgnoreCaseAndWs(sql, "CREATE") //$NON-NLS-1$					|| StringUtils.startsWithIgnoreCaseAndWs(sql, "ALTER")) { //$NON-NLS-1$				throw new SQLException(Messages.getString("Statement.57"), //$NON-NLS-1$						SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$			}		}	}	/**	 * Method checkNullOrEmptyQuery.	 * 	 * @param sql	 *            the SQL to check	 * 	 * @throws SQLException	 *             if query is null or empty.	 */	protected void checkNullOrEmptyQuery(String sql) throws SQLException {		if (sql == null) {			throw new SQLException(Messages.getString("Statement.59"), //$NON-NLS-1$					SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ //$NON-NLS-2$		}		if (sql.length() == 0) {			throw new SQLException(Messages.getString("Statement.61"), //$NON-NLS-1$					SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ //$NON-NLS-2$		}	}	/**	 * JDBC 2.0 Make the set of commands in the current batch empty. This method	 * is optional.	 * 	 * @exception SQLException	 *                if a database-access error occurs, or the driver does not	 *                support batch statements	 */	public synchronized void clearBatch() throws SQLException {		if (this.batchedArgs != null) {			this.batchedArgs.clear();		}	}	/**	 * After this call, getWarnings returns null until a new warning is reported	 * for this Statement.	 * 	 * @exception SQLException	 *                if a database access error occurs (why?)	 */	public synchronized void clearWarnings() throws SQLException {		this.warningChain = null;	}	/**	 * In many cases, it is desirable to immediately release a Statement's	 * database and JDBC resources instead of waiting for this to happen when it	 * is automatically closed. The close method provides this immediate	 * release.	 * 	 * <p>	 * <B>Note:</B> A Statement is automatically closed when it is garbage	 * collected. When a Statement is closed, its current ResultSet, if one	 * exists, is also closed.	 * </p>	 * 	 * @exception SQLException	 *                if a database access error occurs	 */	public synchronized void close() throws SQLException {		realClose(true);	}	/**	 * Close any open result sets that have been 'held open'	 */	protected void closeAllOpenResults() {		if (this.openResults != null) {			for (Iterator iter = this.openResults.iterator(); iter.hasNext();) {				ResultSet element = (ResultSet) iter.next();				try {					element.realClose(false);				} catch (SQLException sqlEx) {					AssertionFailedException.shouldNotHappen(sqlEx);				}			}			this.openResults.clear();		}	}	/**	 * We only stream result sets when they are forward-only, read-only, and the	 * fetch size has been set to Integer.MIN_VALUE	 * 	 * @return true if this result set should be streamed row at-a-time, rather	 *         than read all at once.	 */	protected boolean createStreamingResultSet() {		return ((this.resultSetType == java.sql.ResultSet.TYPE_FORWARD_ONLY)				&& (this.resultSetConcurrency == java.sql.ResultSet.CONCUR_READ_ONLY) && (this.fetchSize == Integer.MIN_VALUE));	}	/**	 * Workaround for containers that 'check' for sane values of	 * Statement.setFetchSize().	 * 	 * @throws SQLException	 */	public void enableStreamingResults() throws SQLException {		setFetchSize(Integer.MIN_VALUE);		setResultSetType(ResultSet.TYPE_FORWARD_ONLY);	}	/**	 * Execute a SQL statement that may return multiple results. We don't have	 * to worry about this since we do not support multiple ResultSets. You can	 * use getResultSet or getUpdateCount to retrieve the result.	 * 	 * @param sql	 *            any SQL statement	 * 	 * @return true if the next result is a ResulSet, false if it is an update	 *         count or there are no more results	 * 	 * @exception SQLException	 *                if a database access error occurs	 */	public synchronized boolean execute(String sql) throws SQLException {		checkNullOrEmptyQuery(sql);		checkClosed();		char firstNonWsChar = StringUtils.firstNonWsCharUc(sql);		boolean isSelect = true;		if (firstNonWsChar != 'S') {			isSelect = false;			if (this.connection.isReadOnly()) {				throw new SQLException(Messages.getString("Statement.27") //$NON-NLS-1$						+ Messages.getString("Statement.28"), //$NON-NLS-1$						SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$			}		}		if (this.doEscapeProcessing) {			Object escapedSqlResult = EscapeProcessor.escapeSQL(sql,					this.connection.serverSupportsConvertFn());			if (escapedSqlResult instanceof String) {				sql = (String) escapedSqlResult;			} else {				sql = ((EscapeProcessorResult) escapedSqlResult).escapedSql;			}		}		if (this.results != null) {

⌨️ 快捷键说明

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