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

📄 preparedstatement.java

📁 mysql的jdbc驱动
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
/* 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 java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.ObjectOutputStream;import java.io.Reader;import java.io.StringReader;import java.io.UnsupportedEncodingException;import java.math.BigDecimal;import java.net.URL;import java.sql.Array;import java.sql.Clob;import java.sql.ParameterMetaData;import java.sql.Ref;import java.sql.SQLException;import java.sql.Time;import java.sql.Timestamp;import java.sql.Types;import java.text.ParsePosition;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.Locale;import java.util.TimeZone;import com.mysql.jdbc.profiler.ProfilerEvent;/** * A SQL Statement is pre-compiled and stored in a PreparedStatement object. * This object can then be used to efficiently execute this statement multiple * times. *  * <p> * <B>Note:</B> The setXXX methods for setting IN parameter values must specify * types that are compatible with the defined SQL type of the input parameter. * For instance, if the IN parameter has SQL type Integer, then setInt should be * used. * </p> *  * <p> * If arbitrary parameter type conversions are required, then the setObject * method should be used with a target SQL type. * </p> *  * @author Mark Matthews * @version $Id: PreparedStatement.java,v 1.1.2.1 2005/05/13 18:58:38 mmatthews *          Exp $ *  * @see java.sql.ResultSet * @see java.sql.PreparedStatement */public class PreparedStatement extends com.mysql.jdbc.Statement implements		java.sql.PreparedStatement {	class BatchParams {		boolean[] isNull = null;		boolean[] isStream = null;		InputStream[] parameterStreams = null;		byte[][] parameterStrings = null;		int[] streamLengths = null;		BatchParams(byte[][] strings, InputStream[] streams,				boolean[] isStreamFlags, int[] lengths, boolean[] isNullFlags) {			//			// Make copies			//			this.parameterStrings = new byte[strings.length][];			this.parameterStreams = new InputStream[streams.length];			this.isStream = new boolean[isStreamFlags.length];			this.streamLengths = new int[lengths.length];			this.isNull = new boolean[isNullFlags.length];			System.arraycopy(strings, 0, this.parameterStrings, 0,					strings.length);			System.arraycopy(streams, 0, this.parameterStreams, 0,					streams.length);			System.arraycopy(isStreamFlags, 0, this.isStream, 0,					isStreamFlags.length);			System.arraycopy(lengths, 0, this.streamLengths, 0, lengths.length);			System					.arraycopy(isNullFlags, 0, this.isNull, 0,							isNullFlags.length);		}	}	class EndPoint {		int begin;		int end;		EndPoint(int b, int e) {			this.begin = b;			this.end = e;		}	}	class ParseInfo {		char firstStmtChar = 0;		boolean foundLimitClause = false;		boolean foundLoadData = false;		long lastUsed = 0;		int statementLength = 0;		byte[][] staticSql = null;		/**		 * 		 */		public ParseInfo(String sql, Connection conn,				java.sql.DatabaseMetaData dbmd, String encoding,				SingleByteCharsetConverter converter) throws SQLException {			if (sql == null) {				throw new SQLException(Messages						.getString("PreparedStatement.61"), //$NON-NLS-1$						SQLError.SQL_STATE_ILLEGAL_ARGUMENT);			}			this.lastUsed = System.currentTimeMillis();			String quotedIdentifierString = dbmd.getIdentifierQuoteString();			char quotedIdentifierChar = 0;			if ((quotedIdentifierString != null)					&& !quotedIdentifierString.equals(" ") //$NON-NLS-1$					&& (quotedIdentifierString.length() > 0)) {				quotedIdentifierChar = quotedIdentifierString.charAt(0);			}			this.statementLength = sql.length();			ArrayList endpointList = new ArrayList();			boolean inQuotes = false;			char quoteChar = 0;			boolean inQuotedId = false;			int lastParmEnd = 0;			int i;			int pre1 = 0;			int pre2 = 0;			int stopLookingForLimitClause = this.statementLength - 5;			this.foundLimitClause = false;			for (i = 0; i < this.statementLength; ++i) {				char c = sql.charAt(i);				if ((this.firstStmtChar == 0) && !Character.isWhitespace(c)) {					// Determine what kind of statement we're doing (_S_elect,					// _I_nsert, etc.)					this.firstStmtChar = Character.toUpperCase(c);				}				// are we in a quoted identifier?				// (only valid when the id is not inside a 'string')				if (!inQuotes && (quotedIdentifierChar != 0)						&& (c == quotedIdentifierChar)) {					inQuotedId = !inQuotedId;				}				// only respect quotes when not in a quoted identifier				if (!inQuotedId) {					if (inQuotes) {						if ((((c == '\'') || (c == '"')) && c == quoteChar)								&& (pre1 == '\\') && (pre2 != '\\')) {							inQuotes = !inQuotes;							quoteChar = 0;						} else if ((((c == '\'') || (c == '"')) && c == quoteChar)								&& (pre1 != '\\')) {							inQuotes = !inQuotes;							quoteChar = 0;						}					} else {						if (((c == '\'') || (c == '"')) && (pre1 == '\\')								&& (pre2 != '\\')) {							inQuotes = true;							quoteChar = c;						} else if (((c == '\'') || (c == '"'))								&& (pre1 != '\\')) {							inQuotes = true;							quoteChar = c;						}					}				}				if ((c == '?') && !inQuotes) {					endpointList.add(new int[] { lastParmEnd, i });					lastParmEnd = i + 1;				}				if (!inQuotes && (i < stopLookingForLimitClause)) {					if ((c == 'L') || (c == 'l')) {						char posI1 = sql.charAt(i + 1);						if ((posI1 == 'I') || (posI1 == 'i')) {							char posM = sql.charAt(i + 2);							if ((posM == 'M') || (posM == 'm')) {								char posI2 = sql.charAt(i + 3);								if ((posI2 == 'I') || (posI2 == 'i')) {									char posT = sql.charAt(i + 4);									if ((posT == 'T') || (posT == 't')) {										foundLimitClause = true;									}								}							}						}					}				}				pre2 = pre1;				pre1 = c;			}			if (this.firstStmtChar == 'L') {				if (StringUtils.startsWithIgnoreCaseAndWs(sql, "LOAD DATA")) { //$NON-NLS-1$					this.foundLoadData = true;				} else {					this.foundLoadData = false;				}			} else {				this.foundLoadData = false;			}			endpointList.add(new int[] { lastParmEnd, this.statementLength });			this.staticSql = new byte[endpointList.size()][];			char[] asCharArray = null;			for (i = 0; i < this.staticSql.length; i++) {				int[] ep = (int[]) endpointList.get(i);				int end = ep[1];				int begin = ep[0];				int len = end - begin;				if (this.foundLoadData) {					if (asCharArray == null) {						asCharArray = sql.toCharArray();					}										String temp = new String(asCharArray, begin, len);					this.staticSql[i] = temp.getBytes();				} else if (encoding == null) {					byte[] buf = new byte[len];					for (int j = 0; j < len; j++) {						buf[j] = (byte) sql.charAt(begin + j);					}					this.staticSql[i] = buf;				} else {					if (converter != null) {						this.staticSql[i] = StringUtils.getBytes(sql,								converter, encoding, connection										.getServerCharacterEncoding(), begin,								len, connection.parserKnowsUnicode());					} else {						if (asCharArray == null) {							asCharArray = sql.toCharArray();						}												String temp = new String(asCharArray, begin, len);						this.staticSql[i] = StringUtils.getBytes(temp,								encoding, connection										.getServerCharacterEncoding(),								connection.parserKnowsUnicode());					}				}			}		}	}	private final static byte[] HEX_DIGITS = new byte[] { (byte) '0',			(byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5',			(byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A',			(byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F' };	/**	 * Reads length bytes from reader into buf. Blocks until enough input is	 * available	 * 	 * @param reader	 *            DOCUMENT ME!	 * @param buf	 *            DOCUMENT ME!	 * @param length	 *            DOCUMENT ME!	 * 	 * @return DOCUMENT ME!	 * 	 * @throws IOException	 *             DOCUMENT ME!	 */	private static int readFully(Reader reader, char[] buf, int length)			throws IOException {		int numCharsRead = 0;		while (numCharsRead < length) {			int count = reader.read(buf, numCharsRead, length - numCharsRead);			if (count < 0) {				break;			}			numCharsRead += count;		}		return numCharsRead;	}	protected ArrayList batchedGeneratedKeys = null;	private java.sql.DatabaseMetaData dbmd = null;	/**	 * What is the first character of the prepared statement (used to check for	 * SELECT vs. INSERT/UPDATE/DELETE)	 */	protected char firstCharOfStmt = 0;	/** Does the SQL for this statement contain a 'limit' clause? */	protected boolean hasLimitClause = false;	/** Is this query a LOAD DATA query? */	protected boolean isLoadDataQuery = false;	private boolean[] isNull = null;	private boolean[] isStream = null;	protected int numberOfExecutions = 0;	/** The SQL that was passed in to 'prepare' */	protected String originalSql = null;	/** The number of parameters in this PreparedStatement */	protected int parameterCount;	protected MysqlParameterMetadata parameterMetaData;	private InputStream[] parameterStreams = null;	private byte[][] parameterValues = null;	private ParseInfo parseInfo;	private java.sql.ResultSetMetaData pstmtResultMetaData;	protected boolean retrieveGeneratedKeys = false;	private byte[][] staticSqlStrings = null;	private byte[] streamConvertBuf = new byte[4096];	private int[] streamLengths = null;	private SimpleDateFormat tsdf = null;	/**	 * Are we using a version of MySQL where we can use 'true' boolean values?	 */	protected boolean useTrueBoolean = false;	private boolean usingAnsiMode;	/**	 * Constructor used by server-side prepared statements	 * 	 * @param conn	 *            the connection that created us	 * @param catalog	 *            the catalog in use when we were created	 * 	 * @throws SQLException	 *             if an error occurs	 */	protected PreparedStatement(Connection conn, String catalog)			throws SQLException {		super(conn, catalog);	}	/**	 * Constructor for the PreparedStatement class.	 * 	 * @param conn	 *            the connection creating this statement	 * @param sql	 *            the SQL for this statement	 * @param catalog	 *            the catalog/database this statement should be issued against	 * 	 * @throws SQLException	 *             if a database error occurs.	 */	public PreparedStatement(Connection conn, String sql, String catalog)			throws SQLException {		super(conn, catalog);		if (sql == null) {			throw new SQLException(Messages.getString("PreparedStatement.0"), //$NON-NLS-1$					SQLError.SQL_STATE_ILLEGAL_ARGUMENT);		}		this.originalSql = sql;		this.dbmd = this.connection.getMetaData();		this.useTrueBoolean = this.connection.versionMeetsMinimum(3, 21, 23);		this.parseInfo = new ParseInfo(sql, this.connection, this.dbmd,				this.charEncoding, this.charConverter);		initializeFromParseInfo();	}	/**	 * Creates a new PreparedStatement object.	 * 	 * @param conn	 *            the connection creating this statement	 * @param sql	 *            the SQL for this statement	 * @param catalog	 *            the catalog/database this statement should be issued against	 * @param cachedParseInfo	 *            already created parseInfo.	 * 	 * @throws SQLException	 *             DOCUMENT ME!	 */	public PreparedStatement(Connection conn, String sql, String catalog,			ParseInfo cachedParseInfo) throws SQLException {		super(conn, catalog);		if (sql == null) {			throw new SQLException(Messages.getString("PreparedStatement.1"), //$NON-NLS-1$					SQLError.SQL_STATE_ILLEGAL_ARGUMENT);		}		this.originalSql = sql;		this.dbmd = this.connection.getMetaData();		this.useTrueBoolean = this.connection.versionMeetsMinimum(3, 21, 23);		this.parseInfo = cachedParseInfo;		this.usingAnsiMode = !this.connection.useAnsiQuotedIdentifiers();		initializeFromParseInfo();

⌨️ 快捷键说明

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