Method from com.mysql.jdbc.ConnectionImpl Detail: |
protected void abortInternal() throws SQLException {
if (this.io != null) {
try {
this.io.forceClose();
} catch (Throwable t) {
// can't do anything about it, and we're forcibly aborting
}
this.io = null;
}
this.isClosed = true;
}
Clobbers the physical network connection and marks
this connection as closed. |
protected static SQLException appendMessageToException(SQLException sqlEx,
String messageToAppend,
ExceptionInterceptor interceptor) {
String origMessage = sqlEx.getMessage();
String sqlState = sqlEx.getSQLState();
int vendorErrorCode = sqlEx.getErrorCode();
StringBuffer messageBuf = new StringBuffer(origMessage.length()
+ messageToAppend.length());
messageBuf.append(origMessage);
messageBuf.append(messageToAppend);
SQLException sqlExceptionWithNewMessage = SQLError.createSQLException(messageBuf
.toString(), sqlState, vendorErrorCode, interceptor);
//
// Try and maintain the original stack trace,
// only works on JDK-1.4 and newer
//
try {
// Have to do this with reflection, otherwise older JVMs croak
Method getStackTraceMethod = null;
Method setStackTraceMethod = null;
Object theStackTraceAsObject = null;
Class stackTraceElementClass = Class
.forName("java.lang.StackTraceElement");
Class stackTraceElementArrayClass = Array.newInstance(
stackTraceElementClass, new int[] { 0 }).getClass();
getStackTraceMethod = Throwable.class.getMethod("getStackTrace",
new Class[] {});
setStackTraceMethod = Throwable.class.getMethod("setStackTrace",
new Class[] { stackTraceElementArrayClass });
if (getStackTraceMethod != null && setStackTraceMethod != null) {
theStackTraceAsObject = getStackTraceMethod.invoke(sqlEx,
new Object[0]);
setStackTraceMethod.invoke(sqlExceptionWithNewMessage,
new Object[] { theStackTraceAsObject });
}
} catch (NoClassDefFoundError noClassDefFound) {
} catch (NoSuchMethodException noSuchMethodEx) {
} catch (Throwable catchAll) {
}
return sqlExceptionWithNewMessage;
}
|
public void changeUser(String userName,
String newPassword) throws SQLException {
if ((userName == null) || userName.equals("")) {
userName = "";
}
if (newPassword == null) {
newPassword = "";
}
this.io.changeUser(userName, newPassword, this.database);
this.user = userName;
this.password = newPassword;
if (versionMeetsMinimum(4, 1, 0)) {
configureClientCharacterSet(true);
}
setSessionVariables();
setupServerForTruncationChecks();
}
Changes the user on this connection by performing a re-authentication. If
authentication fails, the connection will remain under the context of the
current user. |
protected void checkClosed() throws SQLException {
if (this.isClosed) {
throwConnectionClosedException();
}
}
|
public void clearHasTriedMaster() {
this.hasTriedMasterFlag = false;
}
|
public void clearWarnings() throws SQLException {
// firstWarning = null;
}
After this call, getWarnings returns null until a new warning is reported
for this connection. |
public PreparedStatement clientPrepareStatement(String sql) throws SQLException {
return clientPrepareStatement(sql,
DEFAULT_RESULT_SET_TYPE,
DEFAULT_RESULT_SET_CONCURRENCY);
}
|
public 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;
}
|
public PreparedStatement clientPrepareStatement(String sql,
int[] autoGenKeyIndexes) throws SQLException {
PreparedStatement pStmt = (PreparedStatement) clientPrepareStatement(sql);
pStmt
.setRetrieveGeneratedKeys((autoGenKeyIndexes != null)
&& (autoGenKeyIndexes.length > 0));
return pStmt;
}
|
public PreparedStatement clientPrepareStatement(String sql,
String[] autoGenKeyColNames) throws SQLException {
PreparedStatement pStmt = (PreparedStatement) clientPrepareStatement(sql);
pStmt
.setRetrieveGeneratedKeys((autoGenKeyColNames != null)
&& (autoGenKeyColNames.length > 0));
return pStmt;
}
|
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 = com.mysql.jdbc.PreparedStatement.getInstance(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 = com.mysql.jdbc.PreparedStatement.getInstance(this, nativeSql,
this.database);
}
pStmt.setResultSetType(resultSetType);
pStmt.setResultSetConcurrency(resultSetConcurrency);
return pStmt;
}
|
public PreparedStatement clientPrepareStatement(String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
return clientPrepareStatement(sql, resultSetType, resultSetConcurrency, true);
}
|
public synchronized void close() throws SQLException {
if (this.connectionLifecycleInterceptors != null) {
new IterateBlock(this.connectionLifecycleInterceptors.iterator()) {
void forEach(Object each) throws SQLException {
((ConnectionLifecycleInterceptor)each).close();
}
}.doForAll();
}
realClose(true, true, false, null);
}
In some cases, it is desirable to immediately release a Connection's
database and JDBC resources instead of waiting for them to be
automatically released (cant think why off the top of my head) Note:
A Connection is automatically closed when it is garbage collected.
Certain fatal errors also result in a closed connection. |
public void commit() throws SQLException {
synchronized (getMutex()) {
checkClosed();
try {
if (this.connectionLifecycleInterceptors != null) {
IterateBlock iter = new IterateBlock(this.connectionLifecycleInterceptors.iterator()) {
void forEach(Object each) throws SQLException {
if (!((ConnectionLifecycleInterceptor)each).commit()) {
this.stopIterating = true;
}
}
};
iter.doForAll();
if (!iter.fullIteration()) {
return;
}
}
// no-op if _relaxAutoCommit == true
if (this.autoCommit && !getRelaxAutoCommit()) {
throw SQLError.createSQLException("Can't call commit when autocommit=true", getExceptionInterceptor());
} else if (this.transactionsSupported) {
if (getUseLocalTransactionState() && versionMeetsMinimum(5, 0, 0)) {
if (!this.io.inTransactionOnServer()) {
return; // effectively a no-op
}
}
execSQL(null, "commit", -1, null,
DEFAULT_RESULT_SET_TYPE,
DEFAULT_RESULT_SET_CONCURRENCY, false,
this.database, null,
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, getExceptionInterceptor());
}
throw sqlException;
} finally {
this.needsPing = this.getReconnectAtTxEnd();
}
return;
}
}
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.
Note: MySQL does not support transactions, so this method is a
no-op.
|
protected void createNewIO(boolean isForReconnect) throws SQLException {
// Synchronization Not needed for *new* connections, but defintely for
// connections going through fail-over, since we might get the
// new connection up and running *enough* to start sending
// cached or still-open server-side prepared statements over
// to the backend before we get a chance to re-prepare them...
synchronized (this.mutex) {
Properties mergedProps = exposeAsProperties(this.props);
long queriesIssuedFailedOverCopy = this.queriesIssuedFailedOver;
this.queriesIssuedFailedOver = 0;
try {
if (!getHighAvailability() && !this.failedOver) {
boolean connectionGood = false;
Exception connectionNotEstablishedBecause = null;
int hostIndex = 0;
//
// TODO: Eventually, when there's enough metadata
// on the server to support it, we should come up
// with a smarter way to pick what server to connect
// to...perhaps even making it 'pluggable'
//
if (getRoundRobinLoadBalance()) {
hostIndex = getNextRoundRobinHostIndex(getURL(),
this.hostList);
}
for (; hostIndex < this.hostListSize; hostIndex++) {
if (hostIndex == 0) {
this.hasTriedMasterFlag = true;
}
try {
String newHostPortPair = (String) this.hostList
.get(hostIndex);
int newPort = 3306;
String[] hostPortPair = NonRegisteringDriver
.parseHostPortPair(newHostPortPair);
String newHost = hostPortPair[NonRegisteringDriver.HOST_NAME_INDEX];
if (newHost == null || StringUtils.isEmptyOrWhitespaceOnly(newHost)) {
newHost = "localhost";
}
if (hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX] != null) {
try {
newPort = Integer
.parseInt(hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX]);
} catch (NumberFormatException nfe) {
throw SQLError.createSQLException(
"Illegal connection port value '"
+ hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX]
+ "'",
SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE, getExceptionInterceptor());
}
}
this.io = new MysqlIO(newHost, newPort, mergedProps,
getSocketFactoryClassName(), this,
getSocketTimeout(),
this.largeRowSizeThreshold.getValueAsInt());
this.io.doHandshake(this.user, this.password,
this.database);
this.connectionId = this.io.getThreadId();
this.isClosed = false;
// save state from old connection
boolean oldAutoCommit = getAutoCommit();
int oldIsolationLevel = this.isolationLevel;
boolean oldReadOnly = isReadOnly();
String oldCatalog = getCatalog();
this.io.setStatementInterceptors(this.statementInterceptors);
// Server properties might be different
// from previous connection, so initialize
// again...
initializePropsFromServer();
if (isForReconnect) {
// Restore state from old connection
setAutoCommit(oldAutoCommit);
if (this.hasIsolationLevels) {
setTransactionIsolation(oldIsolationLevel);
}
setCatalog(oldCatalog);
}
if (hostIndex != 0) {
setFailedOverState();
queriesIssuedFailedOverCopy = 0;
} else {
this.failedOver = false;
queriesIssuedFailedOverCopy = 0;
if (this.hostListSize > 1) {
setReadOnlyInternal(false);
} else {
setReadOnlyInternal(oldReadOnly);
}
}
connectionGood = true;
break; // low-level connection succeeded
} catch (Exception EEE) {
if (this.io != null) {
this.io.forceClose();
}
connectionNotEstablishedBecause = EEE;
connectionGood = false;
if (EEE instanceof SQLException) {
SQLException sqlEx = (SQLException)EEE;
String sqlState = sqlEx.getSQLState();
// If this isn't a communications failure, it will probably never succeed, so
// give up right here and now ....
if ((sqlState == null)
|| !sqlState
.equals(SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE)) {
throw sqlEx;
}
}
// Check next host, it might be up...
if (getRoundRobinLoadBalance()) {
hostIndex = getNextRoundRobinHostIndex(getURL(),
this.hostList) - 1 /* incremented by for loop next time around */;
} else if ((this.hostListSize - 1) == hostIndex) {
throw SQLError.createCommunicationsException(this,
(this.io != null) ? this.io
.getLastPacketSentTimeMs() : 0,
(this.io != null) ? this.io
.getLastPacketReceivedTimeMs() : 0,
EEE, getExceptionInterceptor());
}
}
}
if (!connectionGood) {
// We've really failed!
SQLException chainedEx = SQLError.createSQLException(
Messages.getString("Connection.UnableToConnect"),
SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE, getExceptionInterceptor());
chainedEx.initCause(connectionNotEstablishedBecause);
throw chainedEx;
}
} else {
double timeout = getInitialTimeout();
boolean connectionGood = false;
Exception connectionException = null;
int hostIndex = 0;
if (getRoundRobinLoadBalance()) {
hostIndex = getNextRoundRobinHostIndex(getURL(),
this.hostList);
}
for (; (hostIndex < this.hostListSize) && !connectionGood; hostIndex++) {
if (hostIndex == 0) {
this.hasTriedMasterFlag = true;
}
if (this.preferSlaveDuringFailover && hostIndex == 0) {
hostIndex++;
}
for (int attemptCount = 0; (attemptCount < getMaxReconnects())
&& !connectionGood; attemptCount++) {
try {
if (this.io != null) {
this.io.forceClose();
}
String newHostPortPair = (String) this.hostList
.get(hostIndex);
int newPort = 3306;
String[] hostPortPair = NonRegisteringDriver
.parseHostPortPair(newHostPortPair);
String newHost = hostPortPair[NonRegisteringDriver.HOST_NAME_INDEX];
if (newHost == null || StringUtils.isEmptyOrWhitespaceOnly(newHost)) {
newHost = "localhost";
}
if (hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX] != null) {
try {
newPort = Integer
.parseInt(hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX]);
} catch (NumberFormatException nfe) {
throw SQLError.createSQLException(
"Illegal connection port value '"
+ hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX]
+ "'",
SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE, getExceptionInterceptor());
}
}
this.io = new MysqlIO(newHost, newPort,
mergedProps, getSocketFactoryClassName(),
this, getSocketTimeout(),
this.largeRowSizeThreshold.getValueAsInt());
this.io.doHandshake(this.user, this.password,
this.database);
pingInternal(false, 0);
this.connectionId = this.io.getThreadId();
this.isClosed = false;
// save state from old connection
boolean oldAutoCommit = getAutoCommit();
int oldIsolationLevel = this.isolationLevel;
boolean oldReadOnly = isReadOnly();
String oldCatalog = getCatalog();
this.io.setStatementInterceptors(this.statementInterceptors);
// Server properties might be different
// from previous connection, so initialize
// again...
initializePropsFromServer();
if (isForReconnect) {
// Restore state from old connection
setAutoCommit(oldAutoCommit);
if (this.hasIsolationLevels) {
setTransactionIsolation(oldIsolationLevel);
}
setCatalog(oldCatalog);
}
connectionGood = true;
if (hostIndex != 0) {
setFailedOverState();
queriesIssuedFailedOverCopy = 0;
} else {
this.failedOver = false;
queriesIssuedFailedOverCopy = 0;
if (this.hostListSize > 1) {
setReadOnlyInternal(false);
} else {
setReadOnlyInternal(oldReadOnly);
}
}
break;
} catch (Exception EEE) {
connectionException = EEE;
connectionGood = false;
// Check next host, it might be up...
if (getRoundRobinLoadBalance()) {
hostIndex = getNextRoundRobinHostIndex(getURL(),
this.hostList) - 1 /* incremented by for loop next time around */;
}
}
if (connectionGood) {
break;
}
if (attemptCount > 0) {
try {
Thread.sleep((long) timeout * 1000);
} catch (InterruptedException IE) {
// ignore
}
}
} // end attempts for a single host
} // end iterator for list of hosts
if (!connectionGood) {
// We've really failed!
SQLException chainedEx = SQLError.createSQLException(
Messages.getString("Connection.UnableToConnectWithRetries",
new Object[] {new Integer(getMaxReconnects())}),
SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE, getExceptionInterceptor());
chainedEx.initCause(connectionException);
throw chainedEx;
}
}
if (getParanoid() && !getHighAvailability()
&& (this.hostListSize < = 1)) {
this.password = null;
this.user = null;
}
if (isForReconnect) {
//
// Retrieve any 'lost' prepared statements if re-connecting
//
Iterator statementIter = this.openStatements.values()
.iterator();
//
// We build a list of these outside the map of open statements,
// because
// in the process of re-preparing, we might end up having to
// close
// a prepared statement, thus removing it from the map, and
// generating
// a ConcurrentModificationException
//
Stack serverPreparedStatements = null;
while (statementIter.hasNext()) {
Object statementObj = statementIter.next();
if (statementObj instanceof ServerPreparedStatement) {
if (serverPreparedStatements == null) {
serverPreparedStatements = new Stack();
}
serverPreparedStatements.add(statementObj);
}
}
if (serverPreparedStatements != null) {
while (!serverPreparedStatements.isEmpty()) {
((ServerPreparedStatement) serverPreparedStatements
.pop()).rePrepare();
}
}
}
} finally {
this.queriesIssuedFailedOver = queriesIssuedFailedOverCopy;
}
}
}
Creates an IO channel to the server |
public Statement createStatement() throws SQLException {
return createStatement(DEFAULT_RESULT_SET_TYPE,
DEFAULT_RESULT_SET_CONCURRENCY);
}
SQL statements without parameters are normally executed using Statement
objects. If the same SQL statement is executed many times, it is more
efficient to use a PreparedStatement |
public Statement createStatement(int resultSetType,
int resultSetConcurrency) throws SQLException {
checkClosed();
StatementImpl stmt = new com.mysql.jdbc.StatementImpl(this, this.database);
stmt.setResultSetType(resultSetType);
stmt.setResultSetConcurrency(resultSetConcurrency);
return stmt;
}
JDBC 2.0 Same as createStatement() above, but allows the default result
set type and result set concurrency type to be overridden. |
public Statement createStatement(int resultSetType,
int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
if (getPedantic()) {
if (resultSetHoldability != java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT) {
throw SQLError.createSQLException(
"HOLD_CUSRORS_OVER_COMMIT is only supported holdability level",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
}
return createStatement(resultSetType, resultSetConcurrency);
}
|
protected void dumpTestcaseQuery(String query) {
System.err.println(query);
}
|
protected Connection duplicate() throws SQLException {
return new ConnectionImpl( this.origHostToConnectTo,
this.origPortToConnectTo,
this.props,
this.origDatabaseToConnectTo,
this.myURL);
}
|
ResultSetInternalMethods execSQL(StatementImpl callingStatement,
String sql,
int maxRows,
Buffer packet,
int resultSetType,
int resultSetConcurrency,
boolean streamResults,
String catalog,
Field[] cachedMetadata) throws SQLException {
return execSQL(callingStatement, sql, maxRows, packet, resultSetType,
resultSetConcurrency, streamResults,
catalog, cachedMetadata, false);
}
Send a query to the server. Returns one of the ResultSet objects. This is
synchronized, so Statement's queries will be serialized. |
ResultSetInternalMethods execSQL(StatementImpl callingStatement,
String sql,
int maxRows,
Buffer packet,
int resultSetType,
int resultSetConcurrency,
boolean streamResults,
String catalog,
Field[] cachedMetadata,
boolean isBatch) throws SQLException {
//
// Fall-back if the master is back online if we've
// issued queriesBeforeRetryMaster queries since
// we failed over
//
synchronized (this.mutex) {
long queryStartTime = 0;
int endOfQueryPacketPosition = 0;
if (packet != null) {
endOfQueryPacketPosition = packet.getPosition();
}
if (getGatherPerformanceMetrics()) {
queryStartTime = System.currentTimeMillis();
}
this.lastQueryFinishedTime = 0; // we're busy!
if (this.failedOver && this.autoCommit && !isBatch) {
if (shouldFallBack() && !this.executingFailoverReconnect) {
try {
this.executingFailoverReconnect = true;
createNewIO(true);
String connectedHost = this.io.getHost();
if ((connectedHost != null)
&& this.hostList.get(0).equals(connectedHost)) {
this.failedOver = false;
this.queriesIssuedFailedOver = 0;
setReadOnlyInternal(false);
}
} finally {
this.executingFailoverReconnect = false;
}
}
}
if ((getHighAvailability() || this.failedOver)
&& (this.autoCommit || getAutoReconnectForPools())
&& this.needsPing && !isBatch) {
try {
pingInternal(false, 0);
this.needsPing = false;
} catch (Exception Ex) {
createNewIO(true);
}
}
try {
if (packet == null) {
String encoding = null;
if (getUseUnicode()) {
encoding = getEncoding();
}
return this.io.sqlQueryDirect(callingStatement, sql,
encoding, null, maxRows, resultSetType,
resultSetConcurrency, streamResults, catalog,
cachedMetadata);
}
return this.io.sqlQueryDirect(callingStatement, null, null,
packet, maxRows, resultSetType,
resultSetConcurrency, streamResults, catalog,
cachedMetadata);
} catch (java.sql.SQLException sqlE) {
// don't clobber SQL exceptions
if (getDumpQueriesOnException()) {
String extractedSql = extractSqlFromPacket(sql, packet,
endOfQueryPacketPosition);
StringBuffer messageBuf = new StringBuffer(extractedSql
.length() + 32);
messageBuf
.append("\n\nQuery being executed when exception was thrown:\n\n");
messageBuf.append(extractedSql);
sqlE = appendMessageToException(sqlE, messageBuf.toString(), getExceptionInterceptor());
}
if ((getHighAvailability() || this.failedOver)) {
this.needsPing = true;
} else {
String sqlState = sqlE.getSQLState();
if ((sqlState != null)
&& sqlState
.equals(SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE)) {
cleanup(sqlE);
}
}
throw sqlE;
} catch (Exception ex) {
if ((getHighAvailability() || this.failedOver)) {
this.needsPing = true;
} else if (ex instanceof IOException) {
cleanup(ex);
}
SQLException sqlEx = SQLError.createSQLException(
Messages.getString("Connection.UnexpectedException"),
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
sqlEx.initCause(ex);
throw sqlEx;
} finally {
if (getMaintainTimeStats()) {
this.lastQueryFinishedTime = System.currentTimeMillis();
}
if (this.failedOver) {
this.queriesIssuedFailedOver++;
}
if (getGatherPerformanceMetrics()) {
long queryTime = System.currentTimeMillis()
- queryStartTime;
registerQueryExecutionTime(queryTime);
}
}
}
}
|
protected String extractSqlFromPacket(String possibleSqlQuery,
Buffer queryPacket,
int endOfQueryPacketPosition) throws SQLException {
String extractedSql = null;
if (possibleSqlQuery != null) {
if (possibleSqlQuery.length() > getMaxQuerySizeToLog()) {
StringBuffer truncatedQueryBuf = new StringBuffer(
possibleSqlQuery.substring(0, getMaxQuerySizeToLog()));
truncatedQueryBuf.append(Messages.getString("MysqlIO.25"));
extractedSql = truncatedQueryBuf.toString();
} else {
extractedSql = possibleSqlQuery;
}
}
if (extractedSql == null) {
// This is probably from a client-side prepared
// statement
int extractPosition = endOfQueryPacketPosition;
boolean truncated = false;
if (endOfQueryPacketPosition > getMaxQuerySizeToLog()) {
extractPosition = getMaxQuerySizeToLog();
truncated = true;
}
extractedSql = new String(queryPacket.getByteBuffer(), 5,
(extractPosition - 5));
if (truncated) {
extractedSql += Messages.getString("MysqlIO.25"); //$NON-NLS-1$
}
}
return extractedSql;
}
|
protected void finalize() throws Throwable {
cleanup(null);
super.finalize();
}
|
protected StringBuffer generateConnectionCommentBlock(StringBuffer buf) {
buf.append("/* conn id ");
buf.append(getId());
buf.append(" clock: ");
buf.append(System.currentTimeMillis());
buf.append(" */ ");
return buf;
}
|
public int getActiveStatementCount() {
// Might not have one of these if
// not tracking open resources
if (this.openStatements != null) {
synchronized (this.openStatements) {
return this.openStatements.size();
}
}
return 0;
}
|
public boolean getAutoCommit() throws SQLException {
return this.autoCommit;
}
Gets the current auto-commit state |
public int getAutoIncrementIncrement() {
return this.autoIncrementIncrement;
}
|
protected CachedResultSetMetaData getCachedMetaData(String sql) {
if (this.resultSetMetadataCache != null) {
synchronized (this.resultSetMetadataCache) {
return (CachedResultSetMetaData) this.resultSetMetadataCache
.get(sql);
}
}
return null; // no cache exists
}
Returns cached metadata (or null if not cached) for the given query,
which must match _exactly_.
This method is synchronized by the caller on getMutex(), so if
calling this method from internal code in the driver, make sure it's
synchronized on the mutex that guards communication with the server. |
protected Calendar getCalendarInstanceForSessionOrNew() {
if (getDynamicCalendars()) {
return Calendar.getInstance();
}
return getSessionLockedCalendar();
}
Optimization to only use one calendar per-session, or calculate it for
each call, depending on user configuration |
protected synchronized Timer getCancelTimer() {
if (cancelTimer == null) {
boolean createdNamedTimer = false;
// Use reflection magic to try this on JDK's 1.5 and newer, fallback to non-named
// timer on older VMs.
try {
Constructor ctr = Timer.class.getConstructor(new Class[] {String.class, Boolean.TYPE});
cancelTimer = (Timer)ctr.newInstance(new Object[] { "MySQL Statement Cancellation Timer", Boolean.TRUE});
createdNamedTimer = true;
} catch (Throwable t) {
createdNamedTimer = false;
}
if (!createdNamedTimer) {
cancelTimer = new Timer(true);
}
}
return cancelTimer;
}
|
public String getCatalog() throws SQLException {
return this.database;
}
|
protected String getCharacterSetMetadata() {
return this.characterSetMetadata;
}
|
SingleByteCharsetConverter getCharsetConverter(String javaEncodingName) throws SQLException {
if (javaEncodingName == null) {
return null;
}
if (this.usePlatformCharsetConverters) {
return null; // we'll use Java's built-in routines for this
// they're finally fast enough
}
SingleByteCharsetConverter converter = null;
synchronized (this.charsetConverterMap) {
Object asObject = this.charsetConverterMap
.get(javaEncodingName);
if (asObject == CHARSET_CONVERTER_NOT_AVAILABLE_MARKER) {
return null;
}
converter = (SingleByteCharsetConverter)asObject;
if (converter == null) {
try {
converter = SingleByteCharsetConverter.getInstance(
javaEncodingName, this);
if (converter == null) {
this.charsetConverterMap.put(javaEncodingName,
CHARSET_CONVERTER_NOT_AVAILABLE_MARKER);
} else {
this.charsetConverterMap.put(javaEncodingName, converter);
}
} catch (UnsupportedEncodingException unsupEncEx) {
this.charsetConverterMap.put(javaEncodingName,
CHARSET_CONVERTER_NOT_AVAILABLE_MARKER);
converter = null;
}
}
}
return converter;
}
Returns the locally mapped instance of a charset converter (to avoid
overhead of static synchronization). |
protected String getCharsetNameForIndex(int charsetIndex) throws SQLException {
String charsetName = null;
if (getUseOldUTF8Behavior()) {
return getEncoding();
}
if (charsetIndex != MysqlDefs.NO_CHARSET_INFO) {
try {
charsetName = this.indexToCharsetMapping[charsetIndex];
if ("sjis".equalsIgnoreCase(charsetName) ||
"MS932".equalsIgnoreCase(charsetName) /* for JDK6 */) {
// Use our encoding so that code pages like Cp932 work
if (CharsetMapping.isAliasForSjis(getEncoding())) {
charsetName = getEncoding();
}
}
} catch (ArrayIndexOutOfBoundsException outOfBoundsEx) {
throw SQLError.createSQLException(
"Unknown character set index for field '"
+ charsetIndex + "' received from server.",
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
}
// Punt
if (charsetName == null) {
charsetName = getEncoding();
}
} else {
charsetName = getEncoding();
}
return charsetName;
}
Returns the Java character encoding name for the given MySQL server
charset index |
protected TimeZone getDefaultTimeZone() {
return this.defaultTimeZone;
}
|
protected String getErrorMessageEncoding() {
return errorMessageEncoding;
}
|
public ExceptionInterceptor getExceptionInterceptor() {
return this.exceptionInterceptor;
}
|
public int getHoldability() throws SQLException {
return java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
|
protected MysqlIO getIO() throws SQLException {
if ((this.io == null) || this.isClosed) {
throw SQLError.createSQLException(
"Operation not allowed on closed connection",
SQLError.SQL_STATE_CONNECTION_NOT_OPEN, getExceptionInterceptor());
}
return this.io;
}
Returns the IO channel to the server |
long getId() {
return this.connectionId;
}
|
public long getIdleFor() {
if (this.lastQueryFinishedTime == 0) {
return 0;
}
long now = System.currentTimeMillis();
long idleTime = now - this.lastQueryFinishedTime;
return idleTime;
}
NOT JDBC-Compliant, but clients can use this method to determine how long
this connection has been idle. This time (reported in milliseconds) is
updated once a query has completed. |
protected static Connection getInstance(String hostToConnectTo,
int portToConnectTo,
Properties info,
String databaseToConnectTo,
String url) throws SQLException {
if (!Util.isJdbc4()) {
return new ConnectionImpl(hostToConnectTo, portToConnectTo, info,
databaseToConnectTo, url);
}
return (Connection) Util.handleNewInstance(JDBC_4_CONNECTION_CTOR,
new Object[] {
hostToConnectTo, Constants.integerValueOf(portToConnectTo), info,
databaseToConnectTo, url }, null);
}
Creates a connection instance -- We need to provide factory-style methods
so we can support both JDBC3 (and older) and JDBC4 runtimes, otherwise
the class verifier complains when it tries to load JDBC4-only interface
classes that are present in JDBC4 method signatures. |
public Log getLog() throws SQLException {
return this.log;
}
Returns the log mechanism that should be used to log information from/for
this Connection. |
protected int getMaxBytesPerChar(String javaCharsetName) throws SQLException {
// TODO: Check if we can actually run this query at this point in time
String charset = CharsetMapping.getMysqlEncodingForJavaEncoding(
javaCharsetName, this);
if (versionMeetsMinimum(4, 1, 0)) {
Map mapToCheck = null;
if (!getUseDynamicCharsetInfo()) {
mapToCheck = CharsetMapping.STATIC_CHARSET_TO_NUM_BYTES_MAP;
} else {
mapToCheck = this.charsetToNumBytesMap;
synchronized (this.charsetToNumBytesMap) {
if (this.charsetToNumBytesMap.isEmpty()) {
java.sql.Statement stmt = null;
java.sql.ResultSet rs = null;
try {
stmt = getMetadataSafeStatement();
rs = stmt.executeQuery("SHOW CHARACTER SET");
while (rs.next()) {
this.charsetToNumBytesMap.put(rs.getString("Charset"),
Constants.integerValueOf(rs.getInt("Maxlen")));
}
rs.close();
rs = null;
stmt.close();
stmt = null;
} finally {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
}
}
}
}
Integer mbPerChar = (Integer) mapToCheck.get(charset);
if (mbPerChar != null) {
return mbPerChar.intValue();
}
return 1; // we don't know
}
return 1; // we don't know
}
|
public DatabaseMetaData getMetaData() throws SQLException {
return getMetaData(true, true);
}
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 made available
through a DatabaseMetaData object. |
protected Statement getMetadataSafeStatement() throws SQLException {
java.sql.Statement stmt = createStatement();
if (stmt.getMaxRows() != 0) {
stmt.setMaxRows(0);
}
stmt.setEscapeProcessing(false);
if (stmt.getFetchSize() != 0) {
stmt.setFetchSize(0);
}
return stmt;
}
|
Object getMutex() throws SQLException {
if (this.io == null) {
throwConnectionClosedException();
}
reportMetricsIfNeeded();
return this.mutex;
}
Returns the Mutex all queries are locked against |
int getNetBufferLength() {
return this.netBufferLength;
}
Returns the packet buffer size the MySQL server reported upon connection |
public Properties getProperties() {
return this.props;
}
|
public boolean getRequiresEscapingEncoder() {
return requiresEscapingEncoder;
}
|
public String getServerCharacterEncoding() {
if (this.io.versionMeetsMinimum(4, 1, 0)) {
return (String) this.serverVariables.get("character_set_server");
} else {
return (String) this.serverVariables.get("character_set");
}
}
Returns the server's character set |
int getServerMajorVersion() {
return this.io.getServerMajorVersion();
}
|
int getServerMinorVersion() {
return this.io.getServerMinorVersion();
}
|
int getServerSubMinorVersion() {
return this.io.getServerSubMinorVersion();
}
|
public TimeZone getServerTimezoneTZ() {
return this.serverTimezoneTZ;
}
|
String getServerVariable(String variableName) {
if (this.serverVariables != null) {
return (String) this.serverVariables.get(variableName);
}
return null;
}
|
String getServerVersion() {
return this.io.getServerVersion();
}
|
protected Calendar getSessionLockedCalendar() {
return this.sessionCalendar;
}
|
public String getStatementComment() {
return this.statementComment;
}
Returns the comment that will be prepended to all statements
sent to the server. |
protected List getStatementInterceptorsInstances() {
return this.statementInterceptors;
}
|
public int getTransactionIsolation() throws SQLException {
if (this.hasIsolationLevels && !getUseLocalSessionState()) {
java.sql.Statement stmt = null;
java.sql.ResultSet rs = null;
try {
stmt = getMetadataSafeStatement();
String query = null;
int offset = 0;
if (versionMeetsMinimum(4, 0, 3)) {
query = "SELECT @@session.tx_isolation";
offset = 1;
} else {
query = "SHOW VARIABLES LIKE 'transaction_isolation'";
offset = 2;
}
rs = stmt.executeQuery(query);
if (rs.next()) {
String s = rs.getString(offset);
if (s != null) {
Integer intTI = (Integer) mapTransIsolationNameToValue
.get(s);
if (intTI != null) {
return intTI.intValue();
}
}
throw SQLError.createSQLException(
"Could not map transaction isolation '" + s
+ " to a valid JDBC level.",
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
}
throw SQLError.createSQLException(
"Could not retrieve transaction isolation level from server",
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
} finally {
if (rs != null) {
try {
rs.close();
} catch (Exception ex) {
// ignore
;
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception ex) {
// ignore
;
}
stmt = null;
}
}
}
return this.isolationLevel;
}
Get this Connection's current transaction isolation mode. |
public synchronized Map getTypeMap() throws SQLException {
if (this.typeMap == null) {
this.typeMap = new HashMap();
}
return this.typeMap;
}
JDBC 2.0 Get the type-map object associated with this connection. By
default, the map returned is empty. |
String getURL() {
return this.myURL;
}
|
String getUser() {
return this.user;
}
|
protected Calendar getUtcCalendar() {
return this.utcCalendar;
}
|
public SQLWarning getWarnings() throws SQLException {
return null;
}
The first warning reported by calls on this Connection is returned.
Note: Sebsequent warnings will be changed to this
java.sql.SQLWarning |
public boolean hasSameProperties(Connection c) {
return this.props.equals(c.getProperties());
}
|
public boolean hasTriedMaster() {
return this.hasTriedMasterFlag;
}
|
protected void incrementNumberOfPreparedExecutes() {
if (getGatherPerformanceMetrics()) {
this.numberOfPreparedExecutes++;
// We need to increment this, because
// server-side prepared statements bypass
// any execution by the connection itself...
this.numberOfQueriesIssued++;
}
}
|
protected void incrementNumberOfPrepares() {
if (getGatherPerformanceMetrics()) {
this.numberOfPrepares++;
}
}
|
protected void incrementNumberOfResultSetsCreated() {
if (getGatherPerformanceMetrics()) {
this.numberOfResultSetsCreated++;
}
}
|
public void initializeExtension(Extension ex) throws SQLException {
ex.init(this, this.props);
}
|
protected void initializeResultsMetadataFromCache(String sql,
CachedResultSetMetaData cachedMetaData,
ResultSetInternalMethods resultSet) throws SQLException {
if (cachedMetaData == null) {
// read from results
cachedMetaData = new CachedResultSetMetaData();
// assume that users will use named-based
// lookups
resultSet.buildIndexMapping();
resultSet.initializeWithMetadata();
if (resultSet instanceof UpdatableResultSet) {
((UpdatableResultSet)resultSet).checkUpdatability();
}
resultSet.populateCachedMetaData(cachedMetaData);
this.resultSetMetadataCache.put(sql, cachedMetaData);
} else {
resultSet.initializeFromCachedMetaData(cachedMetaData);
resultSet.initializeWithMetadata();
if (resultSet instanceof UpdatableResultSet) {
((UpdatableResultSet)resultSet).checkUpdatability();
}
}
}
Caches CachedResultSetMetaData that has been placed in the cache using
the given SQL as a key.
This method is synchronized by the caller on getMutex(), so if
calling this method from internal code in the driver, make sure it's
synchronized on the mutex that guards communication with the server. |
protected void initializeSafeStatementInterceptors() throws SQLException {
this.isClosed = false;
List unwrappedInterceptors = Util.loadExtensions(this, this.props,
getStatementInterceptors(),
"MysqlIo.BadStatementInterceptor", getExceptionInterceptor());
this.statementInterceptors = new ArrayList(unwrappedInterceptors.size());
for (int i = 0; i < unwrappedInterceptors.size(); i++) {
Object interceptor = unwrappedInterceptors.get(i);
// adapt older versions of statement interceptors, handle the case where something wants v2
// functionality but wants to run with an older driver
if (interceptor instanceof StatementInterceptor) {
if (ReflectiveStatementInterceptorAdapter.getV2PostProcessMethod(interceptor.getClass()) != null) {
this.statementInterceptors.add(new NoSubInterceptorWrapper(new ReflectiveStatementInterceptorAdapter((StatementInterceptor) interceptor)));
} else {
this.statementInterceptors.add(new NoSubInterceptorWrapper(new V1toV2StatementInterceptorAdapter((StatementInterceptor) interceptor)));
}
} else {
this.statementInterceptors.add(new NoSubInterceptorWrapper((StatementInterceptorV2)interceptor));
}
}
}
|
public synchronized boolean isAbonormallyLongQuery(long millisOrNanos) {
if (this.queryTimeCount < 15) {
return false; // need a minimum amount for this to make sense
}
double stddev = Math.sqrt((this.queryTimeSumSquares - ((this.queryTimeSum*this.queryTimeSum) / this.queryTimeCount)) / (this.queryTimeCount - 1));
return millisOrNanos > (this.queryTimeMean + 5 * stddev);
}
|
protected boolean isClientTzUTC() {
return this.isClientTzUTC;
}
|
public boolean isClosed() {
return this.isClosed;
}
|
protected boolean isCursorFetchEnabled() throws SQLException {
return (versionMeetsMinimum(5, 0, 2) && getUseCursorFetch());
}
|
public boolean isInGlobalTx() {
return this.isInGlobalTx;
}
|
public synchronized boolean isMasterConnection() {
return !this.failedOver;
}
Is this connection connected to the first host in the list if
there is a list of servers in the URL? |
public boolean isNoBackslashEscapesSet() {
return this.noBackslashEscapes;
}
Is the server in a sql_mode that doesn't allow us to use \\ to escape
things? |
boolean isReadInfoMsgEnabled() {
return this.readInfoMsg;
}
|
public boolean isReadOnly() throws SQLException {
return this.readOnly;
}
Tests to see if the connection is in Read Only Mode. Note that we cannot
really put the database in read only mode, but we pretend we can by
returning the value of the readOnly flag |
protected boolean isRunningOnJDK13() {
return this.isRunningOnJDK13;
}
|
public synchronized boolean isSameResource(Connection otherConnection) {
if (otherConnection == null) {
return false;
}
boolean directCompare = true;
String otherHost = ((ConnectionImpl)otherConnection).origHostToConnectTo;
String otherOrigDatabase = ((ConnectionImpl)otherConnection).origDatabaseToConnectTo;
String otherCurrentCatalog = ((ConnectionImpl)otherConnection).database;
if (!nullSafeCompare(otherHost, this.origHostToConnectTo)) {
directCompare = false;
} else if (otherHost != null && otherHost.indexOf(',') == -1 &&
otherHost.indexOf(':') == -1) {
// need to check port numbers
directCompare = (((ConnectionImpl)otherConnection).origPortToConnectTo ==
this.origPortToConnectTo);
}
if (directCompare) {
if (!nullSafeCompare(otherOrigDatabase, this.origDatabaseToConnectTo)) { directCompare = false;
directCompare = false;
} else if (!nullSafeCompare(otherCurrentCatalog, this.database)) {
directCompare = false;
}
}
if (directCompare) {
return true;
}
// Has the user explicitly set a resourceId?
String otherResourceId = ((ConnectionImpl)otherConnection).getResourceId();
String myResourceId = getResourceId();
if (otherResourceId != null || myResourceId != null) {
directCompare = nullSafeCompare(otherResourceId, myResourceId);
if (directCompare) {
return true;
}
}
return false;
}
|
protected boolean isServerTzUTC() {
return this.isServerTzUTC;
}
|
public boolean lowerCaseTableNames() {
return this.lowerCaseTableNames;
}
Is the server configured to use lower-case table names only? |
void maxRowsChanged(Statement stmt) {
synchronized (this.mutex) {
if (this.statementsUsingMaxRows == null) {
this.statementsUsingMaxRows = new HashMap();
}
this.statementsUsingMaxRows.put(stmt, stmt);
this.maxRowsChanged = true;
}
}
Has the maxRows value changed? |
public String nativeSQL(String sql) throws SQLException {
if (sql == null) {
return null;
}
Object escapedSqlResult = EscapeProcessor.escapeSQL(sql,
serverSupportsConvertFn(),
this);
if (escapedSqlResult instanceof String) {
return (String) escapedSqlResult;
}
return ((EscapeProcessorResult) escapedSqlResult).escapedSql;
}
A driver may convert the JDBC sql grammar into its system's native SQL
grammar prior to sending it; nativeSQL returns the native form of the
statement that the driver would have sent. |
public boolean parserKnowsUnicode() {
return this.parserKnowsUnicode;
}
|
public void ping() throws SQLException {
pingInternal(true, 0);
}
Detect if the connection is still good |
protected void pingInternal(boolean checkForClosedConnection,
int timeoutMillis) throws SQLException {
if (checkForClosedConnection) {
checkClosed();
}
long pingMillisLifetime = getSelfDestructOnPingSecondsLifetime();
int pingMaxOperations = getSelfDestructOnPingMaxOperations();
if ((pingMillisLifetime > 0 && (System.currentTimeMillis() - this.connectionCreationTimeMillis) > pingMillisLifetime)
|| (pingMaxOperations > 0 && pingMaxOperations < = this.io
.getCommandCount())) {
close();
throw SQLError.createSQLException(Messages
.getString("Connection.exceededConnectionLifetime"),
SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE, getExceptionInterceptor());
}
// Need MySQL-3.22.1, but who uses anything older!?
this.io.sendCommand(MysqlDefs.PING, null, null, false, null, timeoutMillis);
}
|
public CallableStatement prepareCall(String sql) throws SQLException {
return prepareCall(sql, DEFAULT_RESULT_SET_TYPE,
DEFAULT_RESULT_SET_CONCURRENCY);
}
|
public CallableStatement prepareCall(String sql,
int resultSetType,
int resultSetConcurrency) throws SQLException {
if (versionMeetsMinimum(5, 0, 0)) {
CallableStatement cStmt = null;
if (!getCacheCallableStatements()) {
cStmt = parseCallableStatement(sql);
} else {
synchronized (this.parsedCallableStatementCache) {
CompoundCacheKey key = new CompoundCacheKey(getCatalog(), sql);
CallableStatement.CallableStatementParamInfo cachedParamInfo = (CallableStatement.CallableStatementParamInfo) this.parsedCallableStatementCache
.get(key);
if (cachedParamInfo != null) {
cStmt = CallableStatement.getInstance(this, cachedParamInfo);
} else {
cStmt = parseCallableStatement(sql);
cachedParamInfo = cStmt.paramInfo;
this.parsedCallableStatementCache.put(key, cachedParamInfo);
}
}
}
cStmt.setResultSetType(resultSetType);
cStmt.setResultSetConcurrency(resultSetConcurrency);
return cStmt;
}
throw SQLError.createSQLException("Callable statements not " + "supported.",
SQLError.SQL_STATE_DRIVER_NOT_CAPABLE, getExceptionInterceptor());
}
JDBC 2.0 Same as prepareCall() above, but allows the default result set
type and result set concurrency type to be overridden. |
public CallableStatement prepareCall(String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
if (getPedantic()) {
if (resultSetHoldability != java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT) {
throw SQLError.createSQLException(
"HOLD_CUSRORS_OVER_COMMIT is only supported holdability level",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
}
CallableStatement cStmt = (com.mysql.jdbc.CallableStatement) prepareCall(
sql, resultSetType, resultSetConcurrency);
return cStmt;
}
|
public PreparedStatement prepareStatement(String sql) throws SQLException {
return prepareStatement(sql, DEFAULT_RESULT_SET_TYPE,
DEFAULT_RESULT_SET_CONCURRENCY);
}
A SQL statement with or without IN parameters can be pre-compiled and
stored in a PreparedStatement object. This object can then be used to
efficiently execute this statement multiple times.
Note: This method is optimized for handling parametric SQL
statements that benefit from precompilation if the driver supports
precompilation. In this case, the statement is not sent to the database
until the PreparedStatement is executed. This has no direct effect on
users; however it does affect which method throws certain
java.sql.SQLExceptions
MySQL does not support precompilation of statements, so they are handled
by the driver.
|
public PreparedStatement prepareStatement(String sql,
int autoGenKeyIndex) throws SQLException {
java.sql.PreparedStatement pStmt = prepareStatement(sql);
((com.mysql.jdbc.PreparedStatement) pStmt)
.setRetrieveGeneratedKeys(autoGenKeyIndex == java.sql.Statement.RETURN_GENERATED_KEYS);
return pStmt;
}
|
public PreparedStatement prepareStatement(String sql,
int[] autoGenKeyIndexes) throws SQLException {
java.sql.PreparedStatement pStmt = prepareStatement(sql);
((com.mysql.jdbc.PreparedStatement) pStmt)
.setRetrieveGeneratedKeys((autoGenKeyIndexes != null)
&& (autoGenKeyIndexes.length > 0));
return pStmt;
}
|
public PreparedStatement prepareStatement(String sql,
String[] autoGenKeyColNames) throws SQLException {
java.sql.PreparedStatement pStmt = prepareStatement(sql);
((com.mysql.jdbc.PreparedStatement) pStmt)
.setRetrieveGeneratedKeys((autoGenKeyColNames != null)
&& (autoGenKeyColNames.length > 0));
return pStmt;
}
|
public PreparedStatement prepareStatement(String sql,
int resultSetType,
int resultSetConcurrency) throws SQLException {
checkClosed();
//
// FIXME: Create warnings if can't create results of the given
// type or concurrency
//
PreparedStatement pStmt = null;
boolean canServerPrepare = true;
String nativeSql = getProcessEscapeCodesForPrepStmts() ? nativeSQL(sql): sql;
if (this.useServerPreparedStmts && getEmulateUnsupportedPstmts()) {
canServerPrepare = canHandleAsServerPreparedStatement(nativeSql);
}
if (this.useServerPreparedStmts && canServerPrepare) {
if (this.getCachePreparedStatements()) {
synchronized (this.serverSideStatementCache) {
pStmt = (com.mysql.jdbc.ServerPreparedStatement)this.serverSideStatementCache.remove(sql);
if (pStmt != null) {
((com.mysql.jdbc.ServerPreparedStatement)pStmt).setClosed(false);
pStmt.clearParameters();
}
if (pStmt == null) {
try {
pStmt = ServerPreparedStatement.getInstance(this, nativeSql,
this.database, resultSetType, resultSetConcurrency);
if (sql.length() < getPreparedStatementCacheSqlLimit()) {
((com.mysql.jdbc.ServerPreparedStatement)pStmt).isCached = true;
}
pStmt.setResultSetType(resultSetType);
pStmt.setResultSetConcurrency(resultSetConcurrency);
} catch (SQLException sqlEx) {
// Punt, if necessary
if (getEmulateUnsupportedPstmts()) {
pStmt = (PreparedStatement) clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false);
if (sql.length() < getPreparedStatementCacheSqlLimit()) {
this.serverSideStatementCheckCache.put(sql, Boolean.FALSE);
}
} else {
throw sqlEx;
}
}
}
}
} else {
try {
pStmt = ServerPreparedStatement.getInstance(this, nativeSql,
this.database, resultSetType, resultSetConcurrency);
pStmt.setResultSetType(resultSetType);
pStmt.setResultSetConcurrency(resultSetConcurrency);
} catch (SQLException sqlEx) {
// Punt, if necessary
if (getEmulateUnsupportedPstmts()) {
pStmt = (PreparedStatement) clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false);
} else {
throw sqlEx;
}
}
}
} else {
pStmt = (PreparedStatement) clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false);
}
return pStmt;
}
JDBC 2.0 Same as prepareStatement() above, but allows the default result
set type and result set concurrency type to be overridden. |
public PreparedStatement prepareStatement(String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
if (getPedantic()) {
if (resultSetHoldability != java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT) {
throw SQLError.createSQLException(
"HOLD_CUSRORS_OVER_COMMIT is only supported holdability level",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
}
return prepareStatement(sql, resultSetType, resultSetConcurrency);
}
|
protected void realClose(boolean calledExplicitly,
boolean issueRollback,
boolean skipLocalTeardown,
Throwable reason) throws SQLException {
SQLException sqlEx = null;
if (this.isClosed()) {
return;
}
this.forceClosedReason = reason;
try {
if (!skipLocalTeardown) {
if (!getAutoCommit() && issueRollback) {
try {
rollback();
} catch (SQLException ex) {
sqlEx = ex;
}
}
reportMetrics();
if (getUseUsageAdvisor()) {
if (!calledExplicitly) {
String message = "Connection implicitly closed by Driver. You should call Connection.close() from your code to free resources more efficiently and avoid resource leaks.";
this.eventSink.consumeEvent(new ProfilerEvent(
ProfilerEvent.TYPE_WARN, "", //$NON-NLS-1$
this.getCatalog(), this.getId(), -1, -1, System
.currentTimeMillis(), 0, Constants.MILLIS_I18N,
null,
this.pointOfOrigin, message));
}
long connectionLifeTime = System.currentTimeMillis()
- this.connectionCreationTimeMillis;
if (connectionLifeTime < 500) {
String message = "Connection lifetime of < .5 seconds. You might be un-necessarily creating short-lived connections and should investigate connection pooling to be more efficient.";
this.eventSink.consumeEvent(new ProfilerEvent(
ProfilerEvent.TYPE_WARN, "", //$NON-NLS-1$
this.getCatalog(), this.getId(), -1, -1, System
.currentTimeMillis(), 0, Constants.MILLIS_I18N,
null,
this.pointOfOrigin, message));
}
}
try {
closeAllOpenStatements();
} catch (SQLException ex) {
sqlEx = ex;
}
if (this.io != null) {
try {
this.io.quit();
} catch (Exception e) {
;
}
}
} else {
this.io.forceClose();
}
if (this.statementInterceptors != null) {
for (int i = 0; i < this.statementInterceptors.size(); i++) {
((StatementInterceptorV2)this.statementInterceptors.get(i)).destroy();
}
}
if (this.exceptionInterceptor != null) {
this.exceptionInterceptor.destroy();
}
} finally {
this.openStatements = null;
this.io = null;
this.statementInterceptors = null;
this.exceptionInterceptor = null;
ProfilerEventHandlerFactory.removeInstance(this);
synchronized (this) {
if (this.cancelTimer != null) {
this.cancelTimer.cancel();
}
}
this.isClosed = true;
}
if (sqlEx != null) {
throw sqlEx;
}
}
Closes connection and frees resources. |
protected void recachePreparedStatement(ServerPreparedStatement pstmt) throws SQLException {
if (pstmt.isPoolable()) {
synchronized (this.serverSideStatementCache) {
this.serverSideStatementCache.put(pstmt.originalSql, pstmt);
}
}
}
|
protected void registerQueryExecutionTime(long queryTimeMs) {
if (queryTimeMs > this.longestQueryTimeMs) {
this.longestQueryTimeMs = queryTimeMs;
repartitionPerformanceHistogram();
}
addToPerformanceHistogram(queryTimeMs, 1);
if (queryTimeMs < this.shortestQueryTimeMs) {
this.shortestQueryTimeMs = (queryTimeMs == 0) ? 1 : queryTimeMs;
}
this.numberOfQueriesIssued++;
this.totalQueryTimeMs += queryTimeMs;
}
|
void registerStatement(Statement stmt) {
synchronized (this.openStatements) {
this.openStatements.put(stmt, stmt);
}
}
Register a Statement instance as open. |
public void releaseSavepoint(Savepoint arg0) throws SQLException {
// this is a no-op
}
|
protected void reportNumberOfTablesAccessed(int numTablesAccessed) {
if (numTablesAccessed < this.minimumNumberTablesAccessed) {
this.minimumNumberTablesAccessed = numTablesAccessed;
}
if (numTablesAccessed > this.maximumNumberTablesAccessed) {
this.maximumNumberTablesAccessed = numTablesAccessed;
repartitionTablesAccessedHistogram();
}
addToTablesAccessedHistogram(numTablesAccessed, 1);
}
|
public synchronized void reportQueryTime(long millisOrNanos) {
this.queryTimeCount++;
this.queryTimeSum += millisOrNanos;
this.queryTimeSumSquares += (millisOrNanos * millisOrNanos);
this.queryTimeMean = ((this.queryTimeMean * (this.queryTimeCount - 1)) + millisOrNanos)
/ this.queryTimeCount;
}
|
public void resetServerState() throws SQLException {
if (!getParanoid()
&& ((this.io != null) && versionMeetsMinimum(4, 0, 6))) {
changeUser(this.user, this.password);
}
}
Resets the server-side state of this connection. Doesn't work for MySQL
versions older than 4.0.6 or if isParanoid() is set (it will become a
no-op in these cases). Usually only used from connection pooling code. |
public void rollback() throws SQLException {
synchronized (getMutex()) {
checkClosed();
try {
if (this.connectionLifecycleInterceptors != null) {
IterateBlock iter = new IterateBlock(this.connectionLifecycleInterceptors.iterator()) {
void forEach(Object each) throws SQLException {
if (!((ConnectionLifecycleInterceptor)each).rollback()) {
this.stopIterating = true;
}
}
};
iter.doForAll();
if (!iter.fullIteration()) {
return;
}
}
// no-op if _relaxAutoCommit == true
if (this.autoCommit && !getRelaxAutoCommit()) {
throw SQLError.createSQLException(
"Can't call rollback when autocommit=true",
SQLError.SQL_STATE_CONNECTION_NOT_OPEN, getExceptionInterceptor());
} else if (this.transactionsSupported) {
try {
rollbackNoChecks();
} catch (SQLException sqlEx) {
// We ignore non-transactional tables if told to do so
if (getIgnoreNonTxTables()
&& (sqlEx.getErrorCode() != SQLError.ER_WARNING_NOT_COMPLETE_ROLLBACK)) {
throw sqlEx;
}
}
}
} catch (SQLException sqlException) {
if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE
.equals(sqlException.getSQLState())) {
throw SQLError.createSQLException(
"Communications link failure during rollback(). Transaction resolution unknown.",
SQLError.SQL_STATE_TRANSACTION_RESOLUTION_UNKNOWN, getExceptionInterceptor());
}
throw sqlException;
} finally {
this.needsPing = this.getReconnectAtTxEnd();
}
}
}
The method rollback() drops all changes made since the previous
commit/rollback and releases any database locks currently held by the
Connection. |
public void rollback(Savepoint savepoint) throws SQLException {
if (versionMeetsMinimum(4, 0, 14) || versionMeetsMinimum(4, 1, 1)) {
synchronized (getMutex()) {
checkClosed();
try {
if (this.connectionLifecycleInterceptors != null) {
IterateBlock iter = new IterateBlock(this.connectionLifecycleInterceptors.iterator()) {
void forEach(Object each) throws SQLException {
if (!((ConnectionLifecycleInterceptor)each).rollback(savepoint)) {
this.stopIterating = true;
}
}
};
iter.doForAll();
if (!iter.fullIteration()) {
return;
}
}
StringBuffer rollbackQuery = new StringBuffer(
"ROLLBACK TO SAVEPOINT ");
rollbackQuery.append('`');
rollbackQuery.append(savepoint.getSavepointName());
rollbackQuery.append('`');
java.sql.Statement stmt = null;
try {
stmt = getMetadataSafeStatement();
stmt.executeUpdate(rollbackQuery.toString());
} catch (SQLException sqlEx) {
int errno = sqlEx.getErrorCode();
if (errno == 1181) {
String msg = sqlEx.getMessage();
if (msg != null) {
int indexOfError153 = msg.indexOf("153");
if (indexOfError153 != -1) {
throw SQLError.createSQLException("Savepoint '"
+ savepoint.getSavepointName()
+ "' does not exist",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
errno, getExceptionInterceptor());
}
}
}
// We ignore non-transactional tables if told to do so
if (getIgnoreNonTxTables()
&& (sqlEx.getErrorCode() != SQLError.ER_WARNING_NOT_COMPLETE_ROLLBACK)) {
throw sqlEx;
}
if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE
.equals(sqlEx.getSQLState())) {
throw SQLError.createSQLException(
"Communications link failure during rollback(). Transaction resolution unknown.",
SQLError.SQL_STATE_TRANSACTION_RESOLUTION_UNKNOWN, getExceptionInterceptor());
}
throw sqlEx;
} finally {
closeStatement(stmt);
}
} finally {
this.needsPing = this.getReconnectAtTxEnd();
}
}
} else {
throw SQLError.notImplemented();
}
}
|
public PreparedStatement serverPrepareStatement(String sql) throws SQLException {
String nativeSql = getProcessEscapeCodesForPrepStmts() ? nativeSQL(sql): sql;
return ServerPreparedStatement.getInstance(this, nativeSql, this.getCatalog(),
DEFAULT_RESULT_SET_TYPE,
DEFAULT_RESULT_SET_CONCURRENCY);
}
|
public PreparedStatement serverPrepareStatement(String sql,
int autoGenKeyIndex) throws SQLException {
String nativeSql = getProcessEscapeCodesForPrepStmts() ? nativeSQL(sql): sql;
PreparedStatement pStmt = ServerPreparedStatement.getInstance(this, nativeSql, this.getCatalog(),
DEFAULT_RESULT_SET_TYPE,
DEFAULT_RESULT_SET_CONCURRENCY);
pStmt.setRetrieveGeneratedKeys(
autoGenKeyIndex == java.sql.Statement.RETURN_GENERATED_KEYS);
return pStmt;
}
|
public PreparedStatement serverPrepareStatement(String sql,
int[] autoGenKeyIndexes) throws SQLException {
PreparedStatement pStmt = (PreparedStatement) serverPrepareStatement(sql);
pStmt
.setRetrieveGeneratedKeys((autoGenKeyIndexes != null)
&& (autoGenKeyIndexes.length > 0));
return pStmt;
}
|
public PreparedStatement serverPrepareStatement(String sql,
String[] autoGenKeyColNames) throws SQLException {
PreparedStatement pStmt = (PreparedStatement) serverPrepareStatement(sql);
pStmt
.setRetrieveGeneratedKeys((autoGenKeyColNames != null)
&& (autoGenKeyColNames.length > 0));
return pStmt;
}
|
public PreparedStatement serverPrepareStatement(String sql,
int resultSetType,
int resultSetConcurrency) throws SQLException {
String nativeSql = getProcessEscapeCodesForPrepStmts() ? nativeSQL(sql): sql;
return ServerPreparedStatement.getInstance(this, nativeSql, this.getCatalog(),
resultSetType,
resultSetConcurrency);
}
|
public PreparedStatement serverPrepareStatement(String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
if (getPedantic()) {
if (resultSetHoldability != java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT) {
throw SQLError.createSQLException(
"HOLD_CUSRORS_OVER_COMMIT is only supported holdability level",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
}
return serverPrepareStatement(sql, resultSetType, resultSetConcurrency);
}
|
protected boolean serverSupportsConvertFn() throws SQLException {
return versionMeetsMinimum(4, 0, 2);
}
|
public void setAutoCommit(boolean autoCommitFlag) throws SQLException {
synchronized (getMutex()) {
checkClosed();
if (this.connectionLifecycleInterceptors != null) {
IterateBlock iter = new IterateBlock(this.connectionLifecycleInterceptors.iterator()) {
void forEach(Object each) throws SQLException {
if (!((ConnectionLifecycleInterceptor)each).setAutoCommit(autoCommitFlag)) {
this.stopIterating = true;
}
}
};
iter.doForAll();
if (!iter.fullIteration()) {
return;
}
}
if (getAutoReconnectForPools()) {
setHighAvailability(true);
}
try {
if (this.transactionsSupported) {
boolean needsSetOnServer = true;
if (this.getUseLocalSessionState()
&& this.autoCommit == autoCommitFlag) {
needsSetOnServer = false;
} else if (!this.getHighAvailability()) {
needsSetOnServer = this.getIO()
.isSetNeededForAutoCommitMode(autoCommitFlag);
}
// this internal value must be set first as failover depends on
// it
// being set to true to fail over (which is done by most
// app servers and connection pools at the end of
// a transaction), and the driver issues an implicit set
// based on this value when it (re)-connects to a server
// so the value holds across connections
this.autoCommit = autoCommitFlag;
if (needsSetOnServer) {
execSQL(null, autoCommitFlag ? "SET autocommit=1"
: "SET autocommit=0", -1, null,
DEFAULT_RESULT_SET_TYPE,
DEFAULT_RESULT_SET_CONCURRENCY, false,
this.database, null, false);
}
} else {
if ((autoCommitFlag == false) && !getRelaxAutoCommit()) {
throw SQLError.createSQLException("MySQL Versions Older than 3.23.15 "
+ "do not support transactions",
SQLError.SQL_STATE_CONNECTION_NOT_OPEN, getExceptionInterceptor());
}
this.autoCommit = autoCommitFlag;
}
} finally {
if (this.getAutoReconnectForPools()) {
setHighAvailability(false);
}
}
//if (autoCommitFlag) {
// if (this.io.isSetNeededForAutoCommitMode(true)) {
// throw new RuntimeException();
// }
//}
return;
}
}
If a connection is in auto-commit mode, than all its SQL statements will
be executed and committed as individual transactions. Otherwise, its SQL
statements are grouped into transactions that are terminated by either
commit() or rollback(). By default, new connections are in auto- commit
mode. The commit occurs when the statement completes or the next execute
occurs, whichever comes first. In the case of statements returning a
ResultSet, the statement completes when the last row of the ResultSet has
been retrieved or the ResultSet has been closed. In advanced cases, a
single statement may return multiple results as well as output parameter
values. Here the commit occurs when all results and output param values
have been retrieved.
Note: MySQL does not support transactions, so this method is a
no-op.
|
public void setCatalog(String catalog) throws SQLException {
synchronized (getMutex()) {
checkClosed();
if (catalog == null) {
throw SQLError.createSQLException("Catalog can not be null",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
if (this.connectionLifecycleInterceptors != null) {
IterateBlock iter = new IterateBlock(this.connectionLifecycleInterceptors.iterator()) {
void forEach(Object each) throws SQLException {
if (!((ConnectionLifecycleInterceptor)each).setCatalog(catalog)) {
this.stopIterating = true;
}
}
};
iter.doForAll();
if (!iter.fullIteration()) {
return;
}
}
if (getUseLocalSessionState()) {
if (this.lowerCaseTableNames) {
if (this.database.equalsIgnoreCase(catalog)) {
return;
}
} else {
if (this.database.equals(catalog)) {
return;
}
}
}
String quotedId = this.dbmd.getIdentifierQuoteString();
if ((quotedId == null) || quotedId.equals(" ")) {
quotedId = "";
}
StringBuffer query = new StringBuffer("USE ");
query.append(quotedId);
query.append(catalog);
query.append(quotedId);
execSQL(null, query.toString(), -1, null,
DEFAULT_RESULT_SET_TYPE,
DEFAULT_RESULT_SET_CONCURRENCY, false,
this.database, null, false);
this.database = catalog;
}
}
|
public synchronized void setFailedOver(boolean flag) {
if (flag && getRoundRobinLoadBalance()) {
return; // we don't failover for round-robin load-balanced connections
}
this.failedOver = flag;
}
|
public void setHoldability(int arg0) throws SQLException {
// do nothing
}
|
public void setInGlobalTx(boolean flag) {
this.isInGlobalTx = flag;
}
|
public void setPreferSlaveDuringFailover(boolean flag) {
this.preferSlaveDuringFailover = flag;
}
|
void setReadInfoMsgEnabled(boolean flag) {
this.readInfoMsg = flag;
}
|
public void setReadOnly(boolean readOnlyFlag) throws SQLException {
checkClosed();
// Ignore calls to this method if we're failed over and
// we're configured to fail over read-only.
if (this.failedOver && getFailOverReadOnly() && !readOnlyFlag) {
return;
}
setReadOnlyInternal(readOnlyFlag);
}
You can put a connection in read-only mode as a hint to enable database
optimizations Note: setReadOnly cannot be called while in the
middle of a transaction |
protected void setReadOnlyInternal(boolean readOnlyFlag) throws SQLException {
this.readOnly = readOnlyFlag;
}
|
public Savepoint setSavepoint() throws SQLException {
MysqlSavepoint savepoint = new MysqlSavepoint(getExceptionInterceptor());
setSavepoint(savepoint);
return savepoint;
}
|
public synchronized Savepoint setSavepoint(String name) throws SQLException {
MysqlSavepoint savepoint = new MysqlSavepoint(name, getExceptionInterceptor());
setSavepoint(savepoint);
return savepoint;
}
|
public void setStatementComment(String comment) {
this.statementComment = comment;
}
Sets the comment that will be prepended to all statements
sent to the server. Do not use slash-star or star-slash tokens
in the comment as these will be added by the driver itself. |
public synchronized void setTransactionIsolation(int level) throws SQLException {
checkClosed();
if (this.hasIsolationLevels) {
String sql = null;
boolean shouldSendSet = false;
if (getAlwaysSendSetIsolation()) {
shouldSendSet = true;
} else {
if (level != this.isolationLevel) {
shouldSendSet = true;
}
}
if (getUseLocalSessionState()) {
shouldSendSet = this.isolationLevel != level;
}
if (shouldSendSet) {
switch (level) {
case java.sql.Connection.TRANSACTION_NONE:
throw SQLError.createSQLException("Transaction isolation level "
+ "NONE not supported by MySQL", getExceptionInterceptor());
case java.sql.Connection.TRANSACTION_READ_COMMITTED:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED";
break;
case java.sql.Connection.TRANSACTION_READ_UNCOMMITTED:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
break;
case java.sql.Connection.TRANSACTION_REPEATABLE_READ:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
break;
case java.sql.Connection.TRANSACTION_SERIALIZABLE:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE";
break;
default:
throw SQLError.createSQLException("Unsupported transaction "
+ "isolation level '" + level + "'",
SQLError.SQL_STATE_DRIVER_NOT_CAPABLE, getExceptionInterceptor());
}
execSQL(null, sql, -1, null,
DEFAULT_RESULT_SET_TYPE,
DEFAULT_RESULT_SET_CONCURRENCY,false,
this.database, null, false);
this.isolationLevel = level;
}
} else {
throw SQLError.createSQLException("Transaction Isolation Levels are "
+ "not supported on MySQL versions older than 3.23.36.",
SQLError.SQL_STATE_DRIVER_NOT_CAPABLE, getExceptionInterceptor());
}
}
|
public synchronized void setTypeMap(Map map) throws SQLException {
this.typeMap = map;
}
JDBC 2.0 Install a type-map object as the default type-map for this
connection |
public void shutdownServer() throws SQLException {
try {
this.io.sendCommand(MysqlDefs.SHUTDOWN, null, null, false, null, 0);
} catch (Exception ex) {
SQLException sqlEx = SQLError.createSQLException(
Messages.getString("Connection.UnhandledExceptionDuringShutdown"),
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
sqlEx.initCause(ex);
throw sqlEx;
}
}
Used by MiniAdmin to shutdown a MySQL server |
public boolean storesLowerCaseTableName() {
return storesLowerCaseTableName;
}
|
public boolean supportsIsolationLevel() {
return this.hasIsolationLevels;
}
|
public boolean supportsQuotedIdentifiers() {
return this.hasQuotedIdentifiers;
}
|
public boolean supportsTransactions() {
return this.transactionsSupported;
}
|
void throwConnectionClosedException() throws SQLException {
StringBuffer messageBuf = new StringBuffer(
"No operations allowed after connection closed.");
if (this.forcedClosedLocation != null || this.forceClosedReason != null) {
messageBuf
.append("Connection was implicitly closed by the driver.");
}
SQLException ex = SQLError.createSQLException(messageBuf.toString(),
SQLError.SQL_STATE_CONNECTION_NOT_OPEN, getExceptionInterceptor());
if (this.forceClosedReason != null) {
ex.initCause(this.forceClosedReason);
}
throw ex;
}
|
protected void transactionBegun() throws SQLException {
if (this.connectionLifecycleInterceptors != null) {
IterateBlock iter = new IterateBlock(this.connectionLifecycleInterceptors.iterator()) {
void forEach(Object each) throws SQLException {
((ConnectionLifecycleInterceptor)each).transactionBegun();
}
};
iter.doForAll();
}
}
|
protected void transactionCompleted() throws SQLException {
if (this.connectionLifecycleInterceptors != null) {
IterateBlock iter = new IterateBlock(this.connectionLifecycleInterceptors.iterator()) {
void forEach(Object each) throws SQLException {
((ConnectionLifecycleInterceptor)each).transactionCompleted();
}
};
iter.doForAll();
}
}
|
protected void unSafeStatementInterceptors() throws SQLException {
ArrayList unSafedStatementInterceptors = new ArrayList(this.statementInterceptors.size());
this.statementInterceptors = new ArrayList(this.statementInterceptors.size());
for (int i = 0; i < this.statementInterceptors.size(); i++) {
NoSubInterceptorWrapper wrappedInterceptor = (NoSubInterceptorWrapper) this.statementInterceptors.get(i);
unSafedStatementInterceptors.add(wrappedInterceptor.getUnderlyingInterceptor());
}
this.statementInterceptors = unSafedStatementInterceptors;
}
|
void unregisterStatement(Statement stmt) {
if (this.openStatements != null) {
synchronized (this.openStatements) {
this.openStatements.remove(stmt);
}
}
}
Remove the given statement from the list of open statements |
void unsetMaxRows(Statement stmt) throws SQLException {
synchronized (this.mutex) {
if (this.statementsUsingMaxRows != null) {
Object found = this.statementsUsingMaxRows.remove(stmt);
if ((found != null)
&& (this.statementsUsingMaxRows.size() == 0)) {
execSQL(null, "SET OPTION SQL_SELECT_LIMIT=DEFAULT", -1,
null, DEFAULT_RESULT_SET_TYPE,
DEFAULT_RESULT_SET_CONCURRENCY, false,
this.database, null, false);
this.maxRowsChanged = false;
}
}
}
}
Called by statements on their .close() to let the connection know when it
is safe to set the connection back to 'default' row limits. |
boolean useAnsiQuotedIdentifiers() {
return this.useAnsiQuotes;
}
|
boolean useMaxRows() {
synchronized (this.mutex) {
return this.maxRowsChanged;
}
}
|
public boolean versionMeetsMinimum(int major,
int minor,
int subminor) throws SQLException {
checkClosed();
return this.io.versionMeetsMinimum(major, minor, subminor);
}
|