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

📄 connection.java

📁 开发MySql数据库的最新JDBC驱动。
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
						if (this.forcedClosedLocation != null) {				messageBuf.append("\n\n");				messageBuf						.append(" at (stack trace):\n");				messageBuf.append(Util						.stackTraceToString(this.forcedClosedLocation));			}			if (this.forceClosedReason != null) {				if (this.forcedClosedLocation != null) {					messageBuf.append("\n\nDue ");				} else {					messageBuf.append("due ");				}								messageBuf.append("to underlying exception/error:\n");				messageBuf.append(Util						.stackTraceToString(this.forceClosedReason));			}			throw SQLError.createSQLException(messageBuf.toString(),					SQLError.SQL_STATE_CONNECTION_NOT_OPEN);		}	}	/**	 * If useUnicode flag is set and explicit client character encoding isn't	 * specified then assign encoding from server if any.	 * 	 * @throws SQLException	 *             DOCUMENT ME!	 */	private void checkServerEncoding() throws SQLException {		if (getUseUnicode() && (getEncoding() != null)) {			// spec'd by client, don't map			return;		}		String serverEncoding = (String) this.serverVariables				.get("character_set");		if (serverEncoding == null) {			// must be 4.1.1 or newer?			serverEncoding = (String) this.serverVariables					.get("character_set_server");		}		String mappedServerEncoding = null;		if (serverEncoding != null) {			mappedServerEncoding = CharsetMapping					.getJavaEncodingForMysqlEncoding(serverEncoding							.toUpperCase(Locale.ENGLISH), this);		}		//		// First check if we can do the encoding ourselves		//		if (!getUseUnicode() && (mappedServerEncoding != null)) {			SingleByteCharsetConverter converter = getCharsetConverter(mappedServerEncoding);			if (converter != null) { // we know how to convert this ourselves				setUseUnicode(true); // force the issue				setEncoding(mappedServerEncoding);				return;			}		}		//		// Now, try and find a Java I/O converter that can do		// the encoding for us		//		if (serverEncoding != null) {			if (mappedServerEncoding == null) {				// We don't have a mapping for it, so try				// and canonicalize the name....				if (Character.isLowerCase(serverEncoding.charAt(0))) {					char[] ach = serverEncoding.toCharArray();					ach[0] = Character.toUpperCase(serverEncoding.charAt(0));					setEncoding(new String(ach));				}			}			if (mappedServerEncoding == null) {				throw SQLError.createSQLException("Unknown character encoding on server '"						+ serverEncoding						+ "', use 'characterEncoding=' property "						+ " to provide correct mapping",						SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);			}			//			// Attempt to use the encoding, and bail out if it			// can't be used			//			try {				"abc".getBytes(mappedServerEncoding);				setEncoding(mappedServerEncoding);				setUseUnicode(true);			} catch (UnsupportedEncodingException UE) {				throw SQLError.createSQLException(						"The driver can not map the character encoding '"								+ getEncoding()								+ "' that your server is using "								+ "to a character encoding your JVM understands. You "								+ "can specify this mapping manually by adding \"useUnicode=true\" "								+ "as well as \"characterEncoding=[an_encoding_your_jvm_understands]\" "								+ "to your JDBC URL.", "0S100");			}		}	}	/**	 * Set transaction isolation level to the value received from server if any.	 * Is called by connectionInit(...)	 * 	 * @throws SQLException	 *             DOCUMENT ME!	 */	private void checkTransactionIsolationLevel() throws SQLException {		String txIsolationName = null;		if (versionMeetsMinimum(4, 0, 3)) {			txIsolationName = "tx_isolation";		} else {			txIsolationName = "transaction_isolation";		}		String s = (String) this.serverVariables.get(txIsolationName);		if (s != null) {			Integer intTI = (Integer) mapTransIsolationNameToValue.get(s);			if (intTI != null) {				this.isolationLevel = intTI.intValue();			}		}	}	/**	 * Destroys this connection and any underlying resources	 * 	 * @param fromWhere	 *            DOCUMENT ME!	 * @param whyCleanedUp	 *            DOCUMENT ME!	 */	private void cleanup(Throwable whyCleanedUp) {		try {			if ((this.io != null) && !isClosed()) {				realClose(false, false, false, whyCleanedUp);			} else if (this.io != null) {				this.io.forceClose();			}		} catch (SQLException sqlEx) {			// ignore, we're going away.			;		}		this.isClosed = true;	}	/**	 * After this call, getWarnings returns null until a new warning is reported	 * for this connection.	 * 	 * @exception SQLException	 *                if a database access error occurs	 */	public void clearWarnings() throws SQLException {		// firstWarning = null;	}	/**	 * DOCUMENT ME!	 * 	 * @param sql	 *            DOCUMENT ME!	 * @return DOCUMENT ME!	 * @throws SQLException	 *             DOCUMENT ME!	 */	public PreparedStatement clientPrepareStatement(String sql)			throws SQLException {		return clientPrepareStatement(sql,				java.sql.ResultSet.TYPE_SCROLL_SENSITIVE,				java.sql.ResultSet.CONCUR_READ_ONLY);	}		/**	 * @see Connection#prepareStatement(String, int)	 */	public java.sql.PreparedStatement clientPrepareStatement(String sql,			int autoGenKeyIndex) throws SQLException {		java.sql.PreparedStatement pStmt = clientPrepareStatement(sql);		((com.mysql.jdbc.PreparedStatement) pStmt)				.setRetrieveGeneratedKeys(autoGenKeyIndex == java.sql.Statement.RETURN_GENERATED_KEYS);		return pStmt;	}	/**	 * DOCUMENT ME!	 * 	 * @param sql	 *            DOCUMENT ME!	 * @param resultSetType	 *            DOCUMENT ME!	 * @param resultSetConcurrency	 *            DOCUMENT ME!	 * @return DOCUMENT ME!	 * @throws SQLException	 *             DOCUMENT ME!	 */	public PreparedStatement clientPrepareStatement(String sql,			int resultSetType, int resultSetConcurrency) throws SQLException {		return clientPrepareStatement(sql, resultSetType, resultSetConcurrency, true);	}		protected PreparedStatement clientPrepareStatement(String sql,			int resultSetType, int resultSetConcurrency, 			boolean processEscapeCodesIfNeeded) throws SQLException {		checkClosed();		String nativeSql = processEscapeCodesIfNeeded && getProcessEscapeCodesForPrepStmts() ? nativeSQL(sql): sql;				PreparedStatement pStmt = null;		if (getCachePreparedStatements()) {			synchronized (this.cachedPreparedStatementParams) {				PreparedStatement.ParseInfo pStmtInfo = (PreparedStatement.ParseInfo) this.cachedPreparedStatementParams						.get(nativeSql);					if (pStmtInfo == null) {					pStmt = new com.mysql.jdbc.PreparedStatement(this, nativeSql,							this.database);						PreparedStatement.ParseInfo parseInfo = pStmt.getParseInfo();						if (parseInfo.statementLength < getPreparedStatementCacheSqlLimit()) {						if (this.cachedPreparedStatementParams.size() >= getPreparedStatementCacheSize()) {							Iterator oldestIter = this.cachedPreparedStatementParams									.keySet().iterator();							long lruTime = Long.MAX_VALUE;							String oldestSql = null;								while (oldestIter.hasNext()) {								String sqlKey = (String) oldestIter.next();								PreparedStatement.ParseInfo lruInfo = (PreparedStatement.ParseInfo) this.cachedPreparedStatementParams										.get(sqlKey);									if (lruInfo.lastUsed < lruTime) {									lruTime = lruInfo.lastUsed;									oldestSql = sqlKey;								}							}								if (oldestSql != null) {								this.cachedPreparedStatementParams										.remove(oldestSql);							}						}							this.cachedPreparedStatementParams.put(nativeSql, pStmt								.getParseInfo());					}				} else {					pStmtInfo.lastUsed = System.currentTimeMillis();					pStmt = new com.mysql.jdbc.PreparedStatement(this, nativeSql,							this.database, pStmtInfo);				}			}		} else {			pStmt = new com.mysql.jdbc.PreparedStatement(this, nativeSql,					this.database);		}		pStmt.setResultSetType(resultSetType);		pStmt.setResultSetConcurrency(resultSetConcurrency);		return pStmt;	}		public void close() throws SQLException {		realClose(true, true, false, null);	}	/**	 * Closes all currently open statements.	 * 	 * @throws SQLException	 *             DOCUMENT ME!	 */	private void closeAllOpenStatements() throws SQLException {		SQLException postponedException = null;		if (this.openStatements != null) {			List currentlyOpenStatements = new ArrayList(); // we need this to			// avoid			// ConcurrentModificationEx			for (Iterator iter = this.openStatements.keySet().iterator(); iter					.hasNext();) {				currentlyOpenStatements.add(iter.next());			}			int numStmts = currentlyOpenStatements.size();			for (int i = 0; i < numStmts; i++) {				Statement stmt = (Statement) currentlyOpenStatements.get(i);				try {					stmt.realClose(false, true);				} catch (SQLException sqlEx) {					postponedException = sqlEx; // throw it later, cleanup all					// statements first				}			}			if (postponedException != null) {				throw postponedException;			}		}	}	private void closeStatement(java.sql.Statement stmt) {		if (stmt != null) {			try {				stmt.close();			} catch (SQLException sqlEx) {				; // ignore			}			stmt = null;		}	}	// --------------------------JDBC 2.0-----------------------------	/**	 * The method commit() makes all changes made since the previous	 * commit/rollback permanent and releases any database locks currently held	 * by the Connection. This method should only be used when auto-commit has	 * been disabled.	 * <p>	 * <b>Note:</b> MySQL does not support transactions, so this method is a	 * no-op.	 * </p>	 * 	 * @exception SQLException	 *                if a database access error occurs	 * @see setAutoCommit	 */	public void commit() throws SQLException {		synchronized (getMutex()) {			checkClosed();				try {				// no-op if _relaxAutoCommit == true				if (this.autoCommit && !getRelaxAutoCommit()) {					throw SQLError.createSQLException("Can't call commit when autocommit=true");				} else if (this.transactionsSupported) {					if (getUseLocalSessionState() && versionMeetsMinimum(5, 0, 0)) {						if (!this.io.inTransactionOnServer()) {							return; // effectively a no-op						}					}										execSQL(null, "commit", -1, null,							java.sql.ResultSet.TYPE_FORWARD_ONLY,							java.sql.ResultSet.CONCUR_READ_ONLY, false,							this.database, true,							false);				}			} catch (SQLException sqlException) {				if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE						.equals(sqlException.getSQLState())) {					throw SQLError.createSQLException(							"Communications link failure during commit(). Transaction resolution unknown.",							SQLError.SQL_STATE_TRANSACTION_RESOLUTION_UNKNOWN);				}					throw sqlException;			} finally {				this.needsPing = this.getReconnectAtTxEnd();			}				return;		}	}	/**	 * Configures client-side properties for character set information.	 * 	 * @throws SQLException	 *             if unable to configure the specified character set.	 */	private void configureCharsetProperties() throws SQLException {		if (getEncoding() != null) {			// Attempt to use the encoding, and bail out if it			// can't be used			try {				String testString = "abc";				testString.getBytes(getEncoding());			} catch (UnsupportedEncodingException UE) {				// Try the MySQL character encoding, then....				String oldEncoding = getEncoding();				setEncoding(CharsetMapping.getJavaEncodingForMysqlEncoding(						oldEncoding, this));				if (getEncoding() == null) {					throw SQLError.createSQLException(							"Java does not support the MySQL character encoding "									+ " " + "encoding '" + oldEncoding + "'.",							SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);				}				try {					String testString = "abc";					testString.getBytes(getEncoding());				} catch (UnsupportedEncodingException encodingEx) {					throw SQLError.createSQLException("Unsupported character "							+ "encoding '" + getEncoding() + "'.",							SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);				}			}		}	}	/**	 * Sets up client character set for MySQL-4.1 and newer if the user This	 * must be done before any further communication with the server!	 * 	 * @return true if this routine actually configured the client character	 *         set, or false if the driver needs to use 'older' methods to	 *         detect the character set, as it is connected to a MySQL server	 *         older than 4.1.0	 * @throws SQLException	 *             if an exception happens while sending 'SET NAMES' to the	 *             server, or the server sends character set information that	 *             the client doesn't know about.	 */	private boolean configureClientCharacterSet() throws SQLException {		String realJavaEncoding = getEncoding();		boolean characterSetAlreadyConfigured = false;		try {			if (versionMeetsMinimum(4, 1, 0)) {				characterSetAlreadyConfigured = true;				setUseUnicode(true);				configureCharsetProperties();				realJavaEncoding = getEncoding(); // we need to do this again				// to grab this for				// versions > 4.1.0				try {					// Fault injection for testing server character set indices		            		            if (props != null && props.getProperty("com.mysql.jdbc.faultInjection.serverCharsetIndex") != null) {		            	this.io.serverCharsetIndex = Integer.parseInt(		            			props.getProperty(		            					"com.mysql.jdbc.faultInjection.serverCharsetIndex"));			            }		            					String serverEncodingToSet = 						CharsetMapping.INDEX_TO_CHARSET[this.io.serverCharsetIndex];										if (serverEncodingToSet == null || serverEncodingToSet.length() == 0) {						if (realJava

⌨️ 快捷键说明

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