📄 connection.java
字号:
/* 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.log.Log;import com.mysql.jdbc.log.LogFactory;import com.mysql.jdbc.log.NullLogger;import com.mysql.jdbc.profiler.ProfileEventSink;import com.mysql.jdbc.profiler.ProfilerEvent;import com.mysql.jdbc.util.LRUCache;import java.io.IOException;import java.io.InputStream;import java.io.Reader;import java.io.UnsupportedEncodingException;import java.lang.reflect.Array;import java.lang.reflect.Method;import java.math.BigDecimal;import java.net.URL;import java.sql.Clob;import java.sql.Date;import java.sql.ParameterMetaData;import java.sql.Ref;import java.sql.SQLException;import java.sql.SQLWarning;import java.sql.Savepoint;import java.sql.Time;import java.sql.Timestamp;import java.util.ArrayList;import java.util.Calendar;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Properties;import java.util.Stack;import java.util.StringTokenizer;import java.util.TimeZone;import java.util.TreeMap;/** * A Connection represents a session with a specific database. Within the * context of a Connection, SQL statements are executed and results are * returned. * * <P> * A Connection's database is able to provide information describing its * tables, its supported SQL grammar, its stored procedures, the capabilities * of this connection, etc. This information is obtained with the getMetaData * method. * </p> * * @author Mark Matthews * @version $Id: Connection.java,v 1.31.4.109 2005/02/16 15:51:24 mmatthews Exp $ * * @see java.sql.Connection */public class Connection extends ConnectionProperties implements java.sql.Connection { // The command used to "ping" the database. // Newer versions of MySQL server have a ping() command, // but this works for everything.4 private static final String PING_COMMAND = "SELECT 1"; /** * Map mysql transaction isolation level name to * java.sql.Connection.TRANSACTION_XXX */ private static Map mapTransIsolationNameToValue = null; private static final Map serverConfigByUrl = new HashMap(); private static final Map serverCollationByUrl = new HashMap(); /** * The mapping between MySQL charset names and Java charset names. * Initialized by loadCharacterSetMapping() */ public static Map charsetMap; /** * The mapping between MySQL charset names and the max number of chars * in them. Lazily instantiated via getMaxBytesPerChar(). */ private Map charsetToNumBytesMap; /** Table of multi-byte charsets. Initialized by loadCharacterSetMapping() */ private static Map multibyteCharsetsMap; /** Default logger class name */ protected static final String DEFAULT_LOGGER_CLASS = "com.mysql.jdbc.log.StandardLogger"; /** Logger instance name */ private static final String LOGGER_INSTANCE_NAME = "MySQL"; /** Null logger shared by all connections at startup */ private static final Log NULL_LOGGER = new NullLogger(LOGGER_INSTANCE_NAME); static { loadCharacterSetMapping(); mapTransIsolationNameToValue = new HashMap(8); mapTransIsolationNameToValue.put("READ-UNCOMMITED", new Integer(TRANSACTION_READ_UNCOMMITTED)); mapTransIsolationNameToValue.put("READ-UNCOMMITTED", new Integer(TRANSACTION_READ_UNCOMMITTED)); mapTransIsolationNameToValue.put("READ-COMMITTED", new Integer(TRANSACTION_READ_COMMITTED)); mapTransIsolationNameToValue.put("REPEATABLE-READ", new Integer(TRANSACTION_REPEATABLE_READ)); mapTransIsolationNameToValue.put("SERIALIZABLE", new Integer(TRANSACTION_SERIALIZABLE)); } /** * Marker for character set converter not being available (not written, * multibyte, etc) Used to prevent multiple instantiation requests. */ private static final Object CHARSET_CONVERTER_NOT_AVAILABLE_MARKER = new Object(); private static Map roundRobinStatsMap; private final static int HISTOGRAM_BUCKETS = 20; /** Internal DBMD to use for various database-version specific features */ private DatabaseMetaData dbmd = null; private LRUCache parsedCallableStatementCache; /** The list of host(s) to try and connect to */ private List hostList = null; /** The logger we're going to use */ private Log log = NULL_LOGGER; /** A map of SQL to parsed prepared statement parameters. */ private Map cachedPreparedStatementParams; /** * Holds cached mappings to charset converters to avoid static * synchronization and at the same time save memory (each charset * converter takes approx 65K of static data). */ private Map charsetConverterMap = new HashMap(CharsetMapping.JAVA_TO_MYSQL_CHARSET_MAP .size()); /** A map of currently open statements */ private Map openStatements; /** The map of server variables that we retrieve at connection init. */ private Map serverVariables = null; /** A map of statements that have had setMaxRows() called on them */ private Map statementsUsingMaxRows; /** * The type map for UDTs (not implemented, but used by some third-party * vendors, most notably IBM WebSphere) */ private Map typeMap; /** The I/O abstraction interface (network conn to MySQL server */ private MysqlIO io = null; /** Mutex */ private final Object mutex = new Object(); /** The event sink to use for profiling */ private ProfileEventSink eventSink; /** Properties for this connection specified by user */ private Properties props = null; /** The database we're currently using (called Catalog in JDBC terms). */ private String database = null; /** The hostname we're connected to */ private String host = null; /** The JDBC URL we're using */ private String myURL = null; /** The password we used */ private String password = null; /** The user we're connected as */ private String user = null; /** Why was this connection implicitly closed, if known? (for diagnostics) */ private Throwable forceClosedReason; /** Where was this connection implicitly closed? (for diagnostics) */ private Throwable forcedClosedLocation; /** Point of origin where this Connection was created */ private Throwable pointOfOrigin; private TimeZone defaultTimeZone; /** The timezone of the server */ private TimeZone serverTimezoneTZ = null; private boolean isServerTzUTC = false; private boolean isClientTzUTC = false; /** * We need this 'bootstrapped', because 4.1 and newer will send fields back * with this even before we fill this dynamically from the server. */ private String[] indexToCharsetMapping = CharsetMapping.INDEX_TO_CHARSET; private long[] perfMetricsHistBreakpoints; private int[] perfMetricsHistCounts; /** Are we in autoCommit mode? */ private boolean autoCommit = true; /** Are we failed-over to a non-master host */ private boolean failedOver = false; /** Does the server suuport isolation levels? */ private boolean hasIsolationLevels = false; /** Does this version of MySQL support quoted identifiers? */ private boolean hasQuotedIdentifiers = false; /** Has this connection been closed? */ private boolean isClosed = true; /** Is the server configured to use lower-case table names only? */ private boolean lowerCaseTableNames = false; /** Has the max-rows setting been changed from the default? */ private boolean maxRowsChanged = false; /** Does this connection need to be tested? */ private boolean needsPing = false; private boolean parserKnowsUnicode = false; /** Should we retrieve 'info' messages from the server? */ private boolean readInfoMsg = false; /** Are we in read-only mode? */ private boolean readOnly = false; /** Are transactions supported by the MySQL server we are connected to? */ private boolean transactionsSupported = false; /** Has ANSI_QUOTES been enabled on the server? */ private boolean useAnsiQuotes = false; /** Can we use the "ping" command rather than a query? */ private boolean useFastPing = false; /** * Should we use server-side prepared statements? (auto-detected, but can * be disabled by user) */ private boolean useServerPreparedStmts = false; private double totalQueryTimeMs = 0; /** ID used when profiling */ private int connectionId; /** How many hosts are in the host list? */ private int hostListSize = 0; /** isolation level */ private int isolationLevel = java.sql.Connection.TRANSACTION_READ_COMMITTED; /** * The largest packet we can send (changed once we know what the server * supports, we get this at connection init). */ private int maxAllowedPacket = 65536; private int netBufferLength = 16384; /** The port number we're connected to (defaults to 3306) */ private int port = 3306; /** The point in time when this connection was created */ private long connectionCreationTimeMillis = 0; /** When did the last query finish? */ private long lastQueryFinishedTime = 0; /** * If gathering metrics, what was the execution time of the longest query * so far ? */ private long longestQueryTimeMs = 0; /** When did the master fail? */ private long masterFailTimeMillis = 0L; /** When was the last time we reported metrics? */ private long metricsLastReportedMs; private long numberOfPreparedExecutes = 0; private long numberOfPrepares = 0; private long numberOfQueriesIssued = 0; private long numberOfResultSetsFetched = 0; /** Number of queries we've issued since the master failed */ private long queriesIssuedFailedOver = 0; private long shortestQueryTimeMs = Long.MAX_VALUE; /** * For servers > 4.1.0, what character set is the metadata returned in? */ private String characterSetMetadata = null; /** * The character set we want results and result metadata returned in (null == results in any charset, metadata in UTF-8). */ private String characterSetResultsOnServer = null; private boolean noBackslashEscapes = false; /** * Used only when testing failover functionality for regressions, * causes the failover code to not retry the master first */ private boolean preferSlaveDuringFailover = false; /** * Creates a connection to a MySQL Server. * * @param hostToConnectTo the hostname of the database server * @param portToConnectTo the port number the server is listening on * @param info a Properties[] list holding the user and password * @param databaseToConnectTo the database to connect to * @param url the URL of the connection * @param d the Driver instantation of the connection * * @exception SQLException if a database access error occurs */ Connection(String hostToConnectTo, int portToConnectTo, Properties info, String databaseToConnectTo, String url, NonRegisteringDriver d) throws SQLException { this.connectionCreationTimeMillis = System.currentTimeMillis(); this.pointOfOrigin = new Throwable(); // // Normally, this code would be in initializeDriverProperties, // but we need to do this as early as possible, so we can start // logging to the 'correct' place as early as possible...this.log // points to 'NullLogger' for every connection at startup to avoid // NPEs and the overhead of checking for NULL at every logging call. // // We will reset this to the configured logger during properties // initialization. // this.log = LogFactory.getLogger(getLogger(), LOGGER_INSTANCE_NAME); // We store this per-connection, due to static synchronization // issues in Java's built-in TimeZone class... this.defaultTimeZone = TimeZone.getDefault(); if ("GMT".equalsIgnoreCase(this.defaultTimeZone.getID())) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -