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

📄 statementimpl.java

📁 mysql5.0 JDBC 驱动 放在glassfish或者tomcat的lib文件夹下就可以了
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
/* Copyright  2002-2007 MySQL AB, 2008 Sun Microsystems 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 java.io.InputStream;import java.sql.BatchUpdateException;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.SQLWarning;import java.sql.Types;import java.util.ArrayList;import java.util.Calendar;import java.util.GregorianCalendar;import java.util.Iterator;import java.util.List;import java.util.TimerTask;import com.mysql.jdbc.exceptions.DeadlockTimeoutRollbackMarker;import com.mysql.jdbc.exceptions.MySQLStatementCancelledException;import com.mysql.jdbc.exceptions.MySQLTimeoutException;import com.mysql.jdbc.profiler.ProfilerEvent;import com.mysql.jdbc.profiler.ProfilerEventHandler;import com.mysql.jdbc.profiler.ProfilerEventHandlerFactory;/** * 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 4624 2005-11-28 14:24:29 -0600 (Mon, 28 Nov *          2005) mmatthews $ * * @see java.sql.Statement * @see ResultSetInternalMethods */public class StatementImpl implements Statement {        protected static final String PING_MARKER = "/* ping */";	/**	 * Thread used to implement query timeouts...Eventually we could be more	 * efficient and have one thread with timers, but this is a straightforward	 * and simple way to implement a feature that isn't used all that often.	 */	class CancelTask extends TimerTask {		long connectionId = 0;		SQLException caughtWhileCancelling = null;		StatementImpl toCancel;				CancelTask(StatementImpl cancellee) throws SQLException {			connectionId = connection.getIO().getThreadId();			toCancel = cancellee;		}		public void run() {			Thread cancelThread = new Thread() {				public void run() {					Connection cancelConn = null;					java.sql.Statement cancelStmt = null;					try {						synchronized (cancelTimeoutMutex) {							cancelConn = connection.duplicate();							cancelStmt = cancelConn.createStatement();							cancelStmt.execute("KILL QUERY " + connectionId);							toCancel.wasCancelled = true;							toCancel.wasCancelledByTimeout = true;						}					} catch (SQLException sqlEx) {						caughtWhileCancelling = sqlEx;					} catch (NullPointerException npe) {						// Case when connection closed while starting to cancel						// We can't easily synchronize this, because then one thread						// can't cancel() a running query						// ignore, we shouldn't re-throw this, because the connection's						// already closed, so the statement has been timed out.					} finally {						if (cancelStmt != null) {							try {								cancelStmt.close();							} catch (SQLException sqlEx) {								throw new RuntimeException(sqlEx.toString());							}						}						if (cancelConn != null) {							try {								cancelConn.close();							} catch (SQLException sqlEx) {								throw new RuntimeException(sqlEx.toString());							}						}					}				}			};			cancelThread.start();		}	}	/** Mutex to prevent race between returning query results and noticing    that we're timed-out or cancelled. */	protected Object cancelTimeoutMutex = new Object();	/** 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;	protected boolean wasCancelled = false;	protected boolean wasCancelledByTimeout = false;	/** 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 ConnectionImpl connection = null;	protected long connectionId = 0;	/** 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 ProfilerEventHandler 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 ResultSetInternalMethods results = null;	/** The concurrency for this result set (updatable or not) */	protected int resultSetConcurrency = 0;	/** 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 timeoutInMillis = 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;	/**	 * Should this statement hold results open over .close() irregardless of	 * connection's setting?	 */	protected boolean holdResultsOpenOverClose = false;	protected ArrayList batchedGeneratedKeys = null;	protected boolean retrieveGeneratedKeys = false;	protected boolean continueBatchOnError = false;	protected PingTarget pingTarget = null;		protected boolean useLegacyDatetimeCode;		/**	 * 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 StatementImpl(ConnectionImpl c, String catalog) throws SQLException {		if ((c == null) || c.isClosed()) {			throw SQLError.createSQLException(					Messages.getString("Statement.0"), //$NON-NLS-1$					SQLError.SQL_STATE_CONNECTION_NOT_OPEN); //$NON-NLS-1$ //$NON-NLS-2$		}		this.connection = c;		this.connectionId = this.connection.getId();		this.currentCatalog = catalog;		this.pedantic = this.connection.getPedantic();		this.continueBatchOnError = this.connection.getContinueBatchOnError();		this.useLegacyDatetimeCode = this.connection.getUseLegacyDatetimeCode();				if (!this.connection.getDontTrackOpenResources()) {			this.connection.registerStatement(this);		}		//		// Adjust, if we know it		//		if (this.connection != null) {			this.maxFieldSize = this.connection.getMaxAllowedPacket();			int defaultFetchSize = this.connection.getDefaultFetchSize();			if (defaultFetchSize != 0) {				setFetchSize(defaultFetchSize);			}		}		if (this.connection.getUseUnicode()) {			this.charEncoding = this.connection.getEncoding();			this.charConverter = this.connection					.getCharsetConverter(this.charEncoding);		}		boolean profiling = this.connection.getProfileSql()				|| this.connection.getUseUsageAdvisor() || this.connection.getLogSlowQueries();		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 = ProfilerEventHandlerFactory.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);		}	}	/**	 * Cancels this Statement object if both the DBMS and driver support	 * aborting an SQL statement. This method can be used by one thread to	 * cancel a statement that is being executed by another thread.	 */	public void cancel() throws SQLException {		if (!this.isClosed &&				this.connection != null &&				this.connection.versionMeetsMinimum(5, 0, 0)) {			Connection cancelConn = null;			java.sql.Statement cancelStmt = null;			try {				cancelConn = this.connection.duplicate();				cancelStmt = cancelConn.createStatement();				cancelStmt.execute("KILL QUERY "						+ this.connection.getIO().getThreadId());				this.wasCancelled = true;			} finally {				if (cancelStmt != null) {					cancelStmt.close();				}				if (cancelConn != null) {					cancelConn.close();				}			}		}	}	// --------------------------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 SQLError.createSQLException(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')) {			String noCommentSql = StringUtils.stripComments(sql,					"'\"", "'\"", true, false, true, true);			if (StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "INSERT") //$NON-NLS-1$					|| StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "UPDATE") //$NON-NLS-1$					|| StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DELETE") //$NON-NLS-1$					|| StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DROP") //$NON-NLS-1$					|| StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "CREATE") //$NON-NLS-1$					|| StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "ALTER")) { //$NON-NLS-1$				throw SQLError.createSQLException(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 SQLError.createSQLException(Messages					.getString("Statement.59"), //$NON-NLS-1$					SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ //$NON-NLS-2$		}		if (sql.length() == 0) {			throw SQLError.createSQLException(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 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>

⌨️ 快捷键说明

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