| Method from com.mysql.jdbc.StatementImpl Detail: |
public synchronized void addBatch(String sql) throws SQLException {
if (this.batchedArgs == null) {
this.batchedArgs = new ArrayList();
}
if (sql != null) {
this.batchedArgs.add(sql);
}
}
|
public void cancel() throws SQLException {
if (!this.isClosed &&
this.connection != null &&
this.connection.versionMeetsMinimum(5, 0, 0)) {
Connection cancelConn = null;
java.sql.Statement cancelStmt = null;
try {
cancelConn = this.connection.duplicate();
cancelStmt = cancelConn.createStatement();
cancelStmt.execute("KILL QUERY "
+ this.connection.getIO().getThreadId());
this.wasCancelled = true;
} finally {
if (cancelStmt != null) {
cancelStmt.close();
}
if (cancelConn != null) {
cancelConn.close();
}
}
}
}
Cancels this Statement object if both the DBMS and driver support
aborting an SQL statement. This method can be used by one thread to
cancel a statement that is being executed by another thread. |
protected void checkClosed() throws SQLException {
if (this.isClosed) {
throw SQLError.createSQLException(Messages
.getString("Statement.49"), //$NON-NLS-1$
SQLError.SQL_STATE_CONNECTION_NOT_OPEN, getExceptionInterceptor()); //$NON-NLS-1$
}
}
Checks if closed() has been called, and throws an exception if so |
protected void checkForDml(String sql,
char firstStatementChar) throws SQLException {
if ((firstStatementChar == 'I') || (firstStatementChar == 'U')
|| (firstStatementChar == 'D') || (firstStatementChar == 'A')
|| (firstStatementChar == 'C')) {
String noCommentSql = StringUtils.stripComments(sql,
"'\"", "'\"", true, false, true, true);
if (StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "INSERT") //$NON-NLS-1$
|| StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "UPDATE") //$NON-NLS-1$
|| StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DELETE") //$NON-NLS-1$
|| StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DROP") //$NON-NLS-1$
|| StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "CREATE") //$NON-NLS-1$
|| StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "ALTER")) { //$NON-NLS-1$
throw SQLError.createSQLException(Messages
.getString("Statement.57"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$
}
}
}
Checks if the given SQL query with the given first non-ws char is a DML
statement. Throws an exception if it is. |
protected void checkNullOrEmptyQuery(String sql) throws SQLException {
if (sql == null) {
throw SQLError.createSQLException(Messages
.getString("Statement.59"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$ //$NON-NLS-2$
}
if (sql.length() == 0) {
throw SQLError.createSQLException(Messages
.getString("Statement.61"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
Method checkNullOrEmptyQuery. |
public synchronized void clearBatch() throws SQLException {
if (this.batchedArgs != null) {
this.batchedArgs.clear();
}
}
JDBC 2.0 Make the set of commands in the current batch empty. This method
is optional. |
public void clearWarnings() throws SQLException {
this.warningChain = null;
}
After this call, getWarnings returns null until a new warning is reported
for this Statement. |
public synchronized void close() throws SQLException {
realClose(true, true);
}
In many cases, it is desirable to immediately release a Statement's
database and JDBC resources instead of waiting for this to happen when it
is automatically closed. The close method provides this immediate
release.
Note: A Statement is automatically closed when it is garbage
collected. When a Statement is closed, its current ResultSet, if one
exists, is also closed.
|
protected synchronized void closeAllOpenResults() {
if (this.openResults != null) {
for (Iterator iter = this.openResults.iterator(); iter.hasNext();) {
ResultSetInternalMethods element = (ResultSetInternalMethods) iter.next();
try {
element.realClose(false);
} catch (SQLException sqlEx) {
AssertionFailedException.shouldNotHappen(sqlEx);
}
}
this.openResults.clear();
}
}
Close any open result sets that have been 'held open' |
protected boolean containsOnDuplicateKeyInString(String sql) {
return getOnDuplicateKeyLocation(sql) != -1;
}
|
protected boolean createStreamingResultSet() {
return ((this.resultSetType == java.sql.ResultSet.TYPE_FORWARD_ONLY)
&& (this.resultSetConcurrency == java.sql.ResultSet.CONCUR_READ_ONLY) && (this.fetchSize == Integer.MIN_VALUE));
}
We only stream result sets when they are forward-only, read-only, and the
fetch size has been set to Integer.MIN_VALUE |
public void disableStreamingResults() throws SQLException {
if (this.fetchSize == Integer.MIN_VALUE &&
this.resultSetType == ResultSet.TYPE_FORWARD_ONLY) {
setFetchSize(this.originalFetchSize);
setResultSetType(this.originalResultSetType);
}
}
|
protected void doPingInstead() throws SQLException {
if (this.pingTarget != null) {
this.pingTarget.doPing();
} else {
this.connection.ping();
}
ResultSetInternalMethods fakeSelectOneResultSet = generatePingResultSet();
this.results = fakeSelectOneResultSet;
}
|
public void enableStreamingResults() throws SQLException {
this.originalResultSetType = this.resultSetType;
this.originalFetchSize = this.fetchSize;
setFetchSize(Integer.MIN_VALUE);
setResultSetType(ResultSet.TYPE_FORWARD_ONLY);
}
|
public boolean execute(String sql) throws SQLException {
return execute(sql, false);
}
Execute a SQL statement that may return multiple results. We don't have
to worry about this since we do not support multiple ResultSets. You can
use getResultSet or getUpdateCount to retrieve the result. |
public boolean execute(String sql,
int returnGeneratedKeys) throws SQLException {
if (returnGeneratedKeys == java.sql.Statement.RETURN_GENERATED_KEYS) {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
synchronized (locallyScopedConn.getMutex()) {
// If this is a 'REPLACE' query, we need to be able to parse
// the 'info' message returned from the server to determine
// the actual number of keys generated.
boolean readInfoMsgState = this.connection
.isReadInfoMsgEnabled();
locallyScopedConn.setReadInfoMsgEnabled(true);
try {
return execute(sql, true);
} finally {
locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState);
}
}
}
return execute(sql);
}
|
public boolean execute(String sql,
int[] generatedKeyIndices) throws SQLException {
if ((generatedKeyIndices != null) && (generatedKeyIndices.length > 0)) {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
synchronized (locallyScopedConn.getMutex()) {
this.retrieveGeneratedKeys = true;
// If this is a 'REPLACE' query, we need to be able to parse
// the 'info' message returned from the server to determine
// the actual number of keys generated.
boolean readInfoMsgState = locallyScopedConn
.isReadInfoMsgEnabled();
locallyScopedConn.setReadInfoMsgEnabled(true);
try {
return execute(sql, true);
} finally {
locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState);
}
}
}
return execute(sql);
}
|
public boolean execute(String sql,
String[] generatedKeyNames) throws SQLException {
if ((generatedKeyNames != null) && (generatedKeyNames.length > 0)) {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
synchronized (locallyScopedConn.getMutex()) {
this.retrieveGeneratedKeys = true;
// If this is a 'REPLACE' query, we need to be able to parse
// the 'info' message returned from the server to determine
// the actual number of keys generated.
boolean readInfoMsgState = this.connection
.isReadInfoMsgEnabled();
locallyScopedConn.setReadInfoMsgEnabled(true);
try {
return execute(sql, true);
} finally {
locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState);
}
}
}
return execute(sql);
}
|
public synchronized int[] executeBatch() throws SQLException {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
if (locallyScopedConn.isReadOnly()) {
throw SQLError.createSQLException(Messages
.getString("Statement.34") //$NON-NLS-1$
+ Messages.getString("Statement.35"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$
}
if (this.results != null) {
if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) {
this.results.realClose(false);
}
}
synchronized (locallyScopedConn.getMutex()) {
if (this.batchedArgs == null || this.batchedArgs.size() == 0) {
return new int[0];
}
// we timeout the entire batch, not individual statements
int individualStatementTimeout = this.timeoutInMillis;
this.timeoutInMillis = 0;
CancelTask timeoutTask = null;
try {
resetCancelledState();
this.retrieveGeneratedKeys = true; // The JDBC spec doesn't forbid this, but doesn't provide for it either...we do..
int[] updateCounts = null;
if (this.batchedArgs != null) {
int nbrCommands = this.batchedArgs.size();
this.batchedGeneratedKeys = new ArrayList(this.batchedArgs.size());
boolean multiQueriesEnabled = locallyScopedConn.getAllowMultiQueries();
if (locallyScopedConn.versionMeetsMinimum(4, 1, 1) &&
(multiQueriesEnabled ||
(locallyScopedConn.getRewriteBatchedStatements() &&
nbrCommands > 4))) {
return executeBatchUsingMultiQueries(multiQueriesEnabled, nbrCommands, individualStatementTimeout);
}
if (locallyScopedConn.getEnableQueryTimeouts() &&
individualStatementTimeout != 0
&& locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
timeoutTask = new CancelTask(this);
locallyScopedConn.getCancelTimer().schedule(timeoutTask,
individualStatementTimeout);
}
updateCounts = new int[nbrCommands];
for (int i = 0; i < nbrCommands; i++) {
updateCounts[i] = -3;
}
SQLException sqlEx = null;
int commandIndex = 0;
for (commandIndex = 0; commandIndex < nbrCommands; commandIndex++) {
try {
String sql = (String) this.batchedArgs.get(commandIndex);
updateCounts[commandIndex] = executeUpdate(sql, true, true);
// limit one generated key per OnDuplicateKey statement
getBatchedGeneratedKeys(containsOnDuplicateKeyInString(sql) ? 1 : 0);
} catch (SQLException ex) {
updateCounts[commandIndex] = EXECUTE_FAILED;
if (this.continueBatchOnError &&
!(ex instanceof MySQLTimeoutException) &&
!(ex instanceof MySQLStatementCancelledException) &&
!hasDeadlockOrTimeoutRolledBackTx(ex)) {
sqlEx = ex;
} else {
int[] newUpdateCounts = new int[commandIndex];
if (hasDeadlockOrTimeoutRolledBackTx(ex)) {
for (int i = 0; i < newUpdateCounts.length; i++) {
newUpdateCounts[i] = Statement.EXECUTE_FAILED;
}
} else {
System.arraycopy(updateCounts, 0,
newUpdateCounts, 0, commandIndex);
}
throw new java.sql.BatchUpdateException(ex
.getMessage(), ex.getSQLState(), ex
.getErrorCode(), newUpdateCounts);
}
}
}
if (sqlEx != null) {
throw new java.sql.BatchUpdateException(sqlEx
.getMessage(), sqlEx.getSQLState(), sqlEx
.getErrorCode(), updateCounts);
}
}
if (timeoutTask != null) {
if (timeoutTask.caughtWhileCancelling != null) {
throw timeoutTask.caughtWhileCancelling;
}
timeoutTask.cancel();
timeoutTask = null;
}
return (updateCounts != null) ? updateCounts : new int[0];
} finally {
if (timeoutTask != null) {
timeoutTask.cancel();
}
resetCancelledState();
this.timeoutInMillis = individualStatementTimeout;
clearBatch();
}
}
}
JDBC 2.0 Submit a batch of commands to the database for execution. This
method is optional. |
public ResultSet executeQuery(String sql) throws SQLException {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
synchronized (locallyScopedConn.getMutex()) {
this.retrieveGeneratedKeys = false;
resetCancelledState();
checkNullOrEmptyQuery(sql);
boolean doStreaming = createStreamingResultSet();
// Adjust net_write_timeout to a higher value if we're
// streaming result sets. More often than not, someone runs into
// an issue where they blow net_write_timeout when using this
// feature, and if they're willing to hold a result set open
// for 30 seconds or more, one more round-trip isn't going to hurt
//
// This is reset by RowDataDynamic.close().
if (doStreaming
&& this.connection.getNetTimeoutForStreamingResults() > 0) {
executeSimpleNonQuery(locallyScopedConn, "SET net_write_timeout="
+ this.connection.getNetTimeoutForStreamingResults());
}
if (this.doEscapeProcessing) {
Object escapedSqlResult = EscapeProcessor.escapeSQL(sql,
locallyScopedConn.serverSupportsConvertFn(), this.connection);
if (escapedSqlResult instanceof String) {
sql = (String) escapedSqlResult;
} else {
sql = ((EscapeProcessorResult) escapedSqlResult).escapedSql;
}
}
char firstStatementChar = StringUtils.firstNonWsCharUc(sql,
findStartOfStatement(sql));
if (sql.charAt(0) == '/') {
if (sql.startsWith(PING_MARKER)) {
doPingInstead();
return this.results;
}
}
checkForDml(sql, firstStatementChar);
if (this.results != null) {
if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) {
this.results.realClose(false);
}
}
CachedResultSetMetaData cachedMetaData = null;
// If there isn't a limit clause in the SQL
// then limit the number of rows to return in
// an efficient manner. Only do this if
// setMaxRows() hasn't been used on any Statements
// generated from the current Connection (saves
// a query, and network traffic).
if (useServerFetch()) {
this.results = createResultSetUsingServerFetch(sql);
return this.results;
}
CancelTask timeoutTask = null;
String oldCatalog = null;
try {
if (locallyScopedConn.getEnableQueryTimeouts() &&
this.timeoutInMillis != 0
&& locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
timeoutTask = new CancelTask(this);
locallyScopedConn.getCancelTimer().schedule(timeoutTask,
this.timeoutInMillis);
}
if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) {
oldCatalog = locallyScopedConn.getCatalog();
locallyScopedConn.setCatalog(this.currentCatalog);
}
//
// Check if we have cached metadata for this query...
//
Field[] cachedFields = null;
if (locallyScopedConn.getCacheResultSetMetadata()) {
cachedMetaData = locallyScopedConn.getCachedMetaData(sql);
if (cachedMetaData != null) {
cachedFields = cachedMetaData.fields;
}
}
if (locallyScopedConn.useMaxRows()) {
// We need to execute this all together
// So synchronize on the Connection's mutex (because
// even queries going through there synchronize
// on the connection
if (StringUtils.indexOfIgnoreCase(sql, "LIMIT") != -1) { //$NON-NLS-1$
this.results = locallyScopedConn.execSQL(this, sql,
this.maxRows, null, this.resultSetType,
this.resultSetConcurrency,
doStreaming,
this.currentCatalog, cachedFields);
} else {
if (this.maxRows < = 0) {
executeSimpleNonQuery(locallyScopedConn,
"SET OPTION SQL_SELECT_LIMIT=DEFAULT");
} else {
executeSimpleNonQuery(locallyScopedConn,
"SET OPTION SQL_SELECT_LIMIT=" + this.maxRows);
}
this.results = locallyScopedConn.execSQL(this, sql, -1,
null, this.resultSetType,
this.resultSetConcurrency,
doStreaming,
this.currentCatalog, cachedFields);
if (oldCatalog != null) {
locallyScopedConn.setCatalog(oldCatalog);
}
}
} else {
this.results = locallyScopedConn.execSQL(this, sql, -1, null,
this.resultSetType, this.resultSetConcurrency,
doStreaming,
this.currentCatalog, cachedFields);
}
if (timeoutTask != null) {
if (timeoutTask.caughtWhileCancelling != null) {
throw timeoutTask.caughtWhileCancelling;
}
timeoutTask.cancel();
timeoutTask = null;
}
synchronized (this.cancelTimeoutMutex) {
if (this.wasCancelled) {
SQLException cause = null;
if (this.wasCancelledByTimeout) {
cause = new MySQLTimeoutException();
} else {
cause = new MySQLStatementCancelledException();
}
resetCancelledState();
throw cause;
}
}
} finally {
if (timeoutTask != null) {
timeoutTask.cancel();
}
if (oldCatalog != null) {
locallyScopedConn.setCatalog(oldCatalog);
}
}
this.lastInsertId = this.results.getUpdateID();
if (cachedMetaData != null) {
locallyScopedConn.initializeResultsMetadataFromCache(sql, cachedMetaData,
this.results);
} else {
if (this.connection.getCacheResultSetMetadata()) {
locallyScopedConn.initializeResultsMetadataFromCache(sql,
null /* will be created */, this.results);
}
}
return this.results;
}
}
Execute a SQL statement that retruns a single ResultSet |
protected void executeSimpleNonQuery(ConnectionImpl c,
String nonQuery) throws SQLException {
c.execSQL(this, nonQuery,
-1, null, ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, false, this.currentCatalog,
null, false).close();
}
|
public int executeUpdate(String sql) throws SQLException {
return executeUpdate(sql, false, false);
}
Execute a SQL INSERT, UPDATE or DELETE statement. In addition SQL
statements that return nothing such as SQL DDL statements can be executed
Any IDs generated for AUTO_INCREMENT fields can be retrieved by casting
this Statement to org.gjt.mm.mysql.Statement and calling the
getLastInsertID() method. |
public int executeUpdate(String sql,
int returnGeneratedKeys) throws SQLException {
if (returnGeneratedKeys == java.sql.Statement.RETURN_GENERATED_KEYS) {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
synchronized (locallyScopedConn.getMutex()) {
// If this is a 'REPLACE' query, we need to be able to parse
// the 'info' message returned from the server to determine
// the actual number of keys generated.
boolean readInfoMsgState = locallyScopedConn
.isReadInfoMsgEnabled();
locallyScopedConn.setReadInfoMsgEnabled(true);
try {
return executeUpdate(sql, false, true);
} finally {
locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState);
}
}
}
return executeUpdate(sql);
}
|
public int executeUpdate(String sql,
int[] generatedKeyIndices) throws SQLException {
if ((generatedKeyIndices != null) && (generatedKeyIndices.length > 0)) {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
synchronized (locallyScopedConn.getMutex()) {
// If this is a 'REPLACE' query, we need to be able to parse
// the 'info' message returned from the server to determine
// the actual number of keys generated.
boolean readInfoMsgState = locallyScopedConn
.isReadInfoMsgEnabled();
locallyScopedConn.setReadInfoMsgEnabled(true);
try {
return executeUpdate(sql, false, true);
} finally {
locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState);
}
}
}
return executeUpdate(sql);
}
|
public int executeUpdate(String sql,
String[] generatedKeyNames) throws SQLException {
if ((generatedKeyNames != null) && (generatedKeyNames.length > 0)) {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
synchronized (locallyScopedConn.getMutex()) {
// If this is a 'REPLACE' query, we need to be able to parse
// the 'info' message returned from the server to determine
// the actual number of keys generated.
boolean readInfoMsgState = this.connection
.isReadInfoMsgEnabled();
locallyScopedConn.setReadInfoMsgEnabled(true);
try {
return executeUpdate(sql, false, true);
} finally {
locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState);
}
}
}
return executeUpdate(sql);
}
|
protected int executeUpdate(String sql,
boolean isBatch,
boolean returnGeneratedKeys) throws SQLException {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
char firstStatementChar = StringUtils.firstAlphaCharUc(sql,
findStartOfStatement(sql));
ResultSetInternalMethods rs = null;
synchronized (locallyScopedConn.getMutex()) {
this.retrieveGeneratedKeys = returnGeneratedKeys;
resetCancelledState();
checkNullOrEmptyQuery(sql);
if (this.doEscapeProcessing) {
Object escapedSqlResult = EscapeProcessor.escapeSQL(sql,
this.connection.serverSupportsConvertFn(), this.connection);
if (escapedSqlResult instanceof String) {
sql = (String) escapedSqlResult;
} else {
sql = ((EscapeProcessorResult) escapedSqlResult).escapedSql;
}
}
if (locallyScopedConn.isReadOnly()) {
throw SQLError.createSQLException(Messages
.getString("Statement.42") //$NON-NLS-1$
+ Messages.getString("Statement.43"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$
}
if (StringUtils.startsWithIgnoreCaseAndWs(sql, "select")) { //$NON-NLS-1$
throw SQLError.createSQLException(Messages
.getString("Statement.46"), //$NON-NLS-1$
"01S03", getExceptionInterceptor()); //$NON-NLS-1$
}
if (this.results != null) {
if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) {
this.results.realClose(false);
}
}
// The checking and changing of catalogs
// must happen in sequence, so synchronize
// on the same mutex that _conn is using
CancelTask timeoutTask = null;
String oldCatalog = null;
try {
if (locallyScopedConn.getEnableQueryTimeouts() &&
this.timeoutInMillis != 0
&& locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
timeoutTask = new CancelTask(this);
locallyScopedConn.getCancelTimer().schedule(timeoutTask,
this.timeoutInMillis);
}
if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) {
oldCatalog = locallyScopedConn.getCatalog();
locallyScopedConn.setCatalog(this.currentCatalog);
}
//
// Only apply max_rows to selects
//
if (locallyScopedConn.useMaxRows()) {
executeSimpleNonQuery(locallyScopedConn,
"SET OPTION SQL_SELECT_LIMIT=DEFAULT");
}
rs = locallyScopedConn.execSQL(this, sql, -1, null,
java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY, false,
this.currentCatalog,
null /* force read of field info on DML */,
isBatch);
if (timeoutTask != null) {
if (timeoutTask.caughtWhileCancelling != null) {
throw timeoutTask.caughtWhileCancelling;
}
timeoutTask.cancel();
timeoutTask = null;
}
synchronized (this.cancelTimeoutMutex) {
if (this.wasCancelled) {
SQLException cause = null;
if (this.wasCancelledByTimeout) {
cause = new MySQLTimeoutException();
} else {
cause = new MySQLStatementCancelledException();
}
resetCancelledState();
throw cause;
}
}
} finally {
if (timeoutTask != null) {
timeoutTask.cancel();
}
if (oldCatalog != null) {
locallyScopedConn.setCatalog(oldCatalog);
}
}
}
this.results = rs;
rs.setFirstCharOfQuery(firstStatementChar);
this.updateCount = rs.getUpdateCount();
int truncatedUpdateCount = 0;
if (this.updateCount > Integer.MAX_VALUE) {
truncatedUpdateCount = Integer.MAX_VALUE;
} else {
truncatedUpdateCount = (int) this.updateCount;
}
this.lastInsertId = rs.getUpdateID();
return truncatedUpdateCount;
}
|
protected int findStartOfStatement(String sql) {
int statementStartPos = 0;
if (StringUtils.startsWithIgnoreCaseAndWs(sql, "/*")) {
statementStartPos = sql.indexOf("*/");
if (statementStartPos == -1) {
statementStartPos = 0;
} else {
statementStartPos += 2;
}
} else if (StringUtils.startsWithIgnoreCaseAndWs(sql, "--")
|| StringUtils.startsWithIgnoreCaseAndWs(sql, "#")) {
statementStartPos = sql.indexOf('\n');
if (statementStartPos == -1) {
statementStartPos = sql.indexOf('\r');
if (statementStartPos == -1) {
statementStartPos = 0;
}
}
}
return statementStartPos;
}
|
protected ResultSetInternalMethods generatePingResultSet() throws SQLException {
Field[] fields = { new Field(null, "1", Types.BIGINT, 1) };
ArrayList rows = new ArrayList();
byte[] colVal = new byte[] { (byte) '1' };
rows.add(new ByteArrayRow(new byte[][] { colVal }, getExceptionInterceptor()));
return (ResultSetInternalMethods) DatabaseMetaData.buildResultSet(fields, rows,
this.connection);
}
|
protected void getBatchedGeneratedKeys(Statement batchedStatement) throws SQLException {
if (this.retrieveGeneratedKeys) {
java.sql.ResultSet rs = null;
try {
rs = batchedStatement.getGeneratedKeys();
while (rs.next()) {
this.batchedGeneratedKeys
.add(new ByteArrayRow(new byte[][] { rs.getBytes(1) }, getExceptionInterceptor()));
}
} finally {
if (rs != null) {
rs.close();
}
}
}
}
|
protected void getBatchedGeneratedKeys(int maxKeys) throws SQLException {
if (this.retrieveGeneratedKeys) {
java.sql.ResultSet rs = null;
try {
if (maxKeys == 0)
rs = getGeneratedKeysInternal();
else
rs = getGeneratedKeysInternal(maxKeys);
while (rs.next()) {
this.batchedGeneratedKeys
.add(new ByteArrayRow(new byte[][] { rs.getBytes(1) }, getExceptionInterceptor()));
}
} finally {
if (rs != null) {
rs.close();
}
}
}
}
|
protected Calendar getCalendarInstanceForSessionOrNew() {
if (this.connection != null) {
return this.connection.getCalendarInstanceForSessionOrNew();
} else {
// punt, no connection around
return new GregorianCalendar();
}
}
Optimization to only use one calendar per-session, or calculate it for
each call, depending on user configuration |
public Connection getConnection() throws SQLException {
return this.connection;
}
JDBC 2.0 Return the Connection that produced the Statement. |
public ExceptionInterceptor getExceptionInterceptor() {
return this.exceptionInterceptor;
}
|
public int getFetchDirection() throws SQLException {
return java.sql.ResultSet.FETCH_FORWARD;
}
JDBC 2.0 Determine the fetch direction. |
public int getFetchSize() throws SQLException {
return this.fetchSize;
}
JDBC 2.0 Determine the default fetch size. |
public synchronized ResultSet getGeneratedKeys() throws SQLException {
if (!this.retrieveGeneratedKeys) {
throw SQLError.createSQLException(Messages.getString("Statement.GeneratedKeysNotRequested"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
if (this.batchedGeneratedKeys == null) {
if (lastQueryIsOnDupKeyUpdate)
return getGeneratedKeysInternal(1);
else
return getGeneratedKeysInternal();
}
Field[] fields = new Field[1];
fields[0] = new Field("", "GENERATED_KEY", Types.BIGINT, 17); //$NON-NLS-1$ //$NON-NLS-2$
fields[0].setConnection(this.connection);
return com.mysql.jdbc.ResultSetImpl.getInstance(this.currentCatalog, fields,
new RowDataStatic(this.batchedGeneratedKeys), this.connection,
this, false);
}
|
protected ResultSet getGeneratedKeysInternal() throws SQLException {
int numKeys = getUpdateCount();
return getGeneratedKeysInternal(numKeys);
}
|
protected synchronized ResultSet getGeneratedKeysInternal(int numKeys) throws SQLException {
Field[] fields = new Field[1];
fields[0] = new Field("", "GENERATED_KEY", Types.BIGINT, 17); //$NON-NLS-1$ //$NON-NLS-2$
fields[0].setConnection(this.connection);
fields[0].setUseOldNameMetadata(true);
ArrayList rowSet = new ArrayList();
long beginAt = getLastInsertID();
if (beginAt < 0) { // looking at an UNSIGNED BIGINT that has overflowed
fields[0].setUnsigned();
}
if (this.results != null) {
String serverInfo = this.results.getServerInfo();
//
// Only parse server info messages for 'REPLACE'
// queries
//
if ((numKeys > 0) && (this.results.getFirstCharOfQuery() == 'R')
&& (serverInfo != null) && (serverInfo.length() > 0)) {
numKeys = getRecordCountFromInfo(serverInfo);
}
if ((beginAt != 0 /* BIGINT UNSIGNED can wrap the protocol representation */) && (numKeys > 0)) {
for (int i = 0; i < numKeys; i++) {
byte[][] row = new byte[1][];
if (beginAt > 0) {
row[0] = Long.toString(beginAt).getBytes();
} else {
byte[] asBytes = new byte[8];
asBytes[7] = (byte) (beginAt & 0xff);
asBytes[6] = (byte) (beginAt > > > 8);
asBytes[5] = (byte) (beginAt > > > 16);
asBytes[4] = (byte) (beginAt > > > 24);
asBytes[3] = (byte) (beginAt > > > 32);
asBytes[2] = (byte) (beginAt > > > 40);
asBytes[1] = (byte) (beginAt > > > 48);
asBytes[0] = (byte) (beginAt > > > 56);
BigInteger val = new BigInteger(1, asBytes);
row[0] = val.toString().getBytes();
}
rowSet.add(new ByteArrayRow(row, getExceptionInterceptor()));
beginAt += this.connection.getAutoIncrementIncrement();
}
}
}
com.mysql.jdbc.ResultSetImpl gkRs = com.mysql.jdbc.ResultSetImpl.getInstance(this.currentCatalog, fields,
new RowDataStatic(rowSet), this.connection, this, false);
this.openResults.add(gkRs);
return gkRs;
}
|
protected int getId() {
return this.statementId;
}
Returns the id used when profiling |
public long getLastInsertID() {
return this.lastInsertId;
}
getLastInsertID returns the value of the auto_incremented key after an
executeQuery() or excute() call.
This gets around the un-threadsafe behavior of "select LAST_INSERT_ID()"
which is tied to the Connection that created this Statement, and
therefore could have had many INSERTS performed before one gets a chance
to call "select LAST_INSERT_ID()".
|
public synchronized InputStream getLocalInfileInputStream() {
return this.localInfileInputStream;
}
|
public long getLongUpdateCount() {
if (this.results == null) {
return -1;
}
if (this.results.reallyResult()) {
return -1;
}
return this.updateCount;
}
getLongUpdateCount returns the current result as an update count, if the
result is a ResultSet or there are no more results, -1 is returned. It
should only be called once per result.
This method returns longs as MySQL server versions newer than 3.22.4
return 64-bit values for update counts
|
public int getMaxFieldSize() throws SQLException {
return this.maxFieldSize;
}
The maxFieldSize limit (in bytes) is the maximum amount of data returned
for any column value; it only applies to BINARY, VARBINARY,
LONGVARBINARY, CHAR, VARCHAR and LONGVARCHAR columns. If the limit is
exceeded, the excess data is silently discarded. |
public int getMaxRows() throws SQLException {
if (this.maxRows < = 0) {
return 0;
}
return this.maxRows;
}
The maxRows limit is set to limit the number of rows that any ResultSet
can contain. If the limit is exceeded, the excess rows are silently
dropped. |
public boolean getMoreResults() throws SQLException {
return getMoreResults(CLOSE_CURRENT_RESULT);
}
getMoreResults moves to a Statement's next result. If it returns true,
this result is a ResulSet. |
public synchronized boolean getMoreResults(int current) throws SQLException {
if (this.results == null) {
return false;
}
boolean streamingMode = createStreamingResultSet();
if (streamingMode) {
if (this.results.reallyResult()) {
while (this.results.next()); // need to drain remaining rows to get to server status
// which tells us whether more results actually exist or not
}
}
ResultSetInternalMethods nextResultSet = this.results.getNextResultSet();
switch (current) {
case java.sql.Statement.CLOSE_CURRENT_RESULT:
if (this.results != null) {
if (!streamingMode) {
this.results.close();
}
this.results.clearNextResult();
}
break;
case java.sql.Statement.CLOSE_ALL_RESULTS:
if (this.results != null) {
if (!streamingMode) {
this.results.close();
}
this.results.clearNextResult();
}
closeAllOpenResults();
break;
case java.sql.Statement.KEEP_CURRENT_RESULT:
if (!this.connection.getDontTrackOpenResources()) {
this.openResults.add(this.results);
}
this.results.clearNextResult(); // nobody besides us should
// ever need this value...
break;
default:
throw SQLError.createSQLException(Messages
.getString("Statement.19"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$
}
this.results = nextResultSet;
if (this.results == null) {
this.updateCount = -1;
this.lastInsertId = -1;
} else if (this.results.reallyResult()) {
this.updateCount = -1;
this.lastInsertId = -1;
} else {
this.updateCount = this.results.getUpdateCount();
this.lastInsertId = this.results.getUpdateID();
}
return ((this.results != null) && this.results.reallyResult()) ? true
: false;
}
|
protected int getOnDuplicateKeyLocation(String sql) {
return StringUtils.indexOfIgnoreCaseRespectMarker(0,
sql, " ON DUPLICATE KEY UPDATE ", "\"'`", "\"'`", !this.connection.isNoBackslashEscapesSet());
}
|
public synchronized int getOpenResultSetCount() {
if (this.openResults != null) {
return this.openResults.size();
}
return 0;
}
|
public int getQueryTimeout() throws SQLException {
return this.timeoutInMillis / 1000;
}
The queryTimeout limit is the number of seconds the driver will wait for
a Statement to execute. If the limit is exceeded, a SQLException is
thrown. |
public ResultSet getResultSet() throws SQLException {
return ((this.results != null) && this.results.reallyResult()) ? (java.sql.ResultSet) this.results
: null;
}
getResultSet returns the current result as a ResultSet. It should only be
called once per result. |
public int getResultSetConcurrency() throws SQLException {
return this.resultSetConcurrency;
}
JDBC 2.0 Determine the result set concurrency. |
public int getResultSetHoldability() throws SQLException {
return java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
|
protected ResultSetInternalMethods getResultSetInternal() {
return this.results;
}
|
public int getResultSetType() throws SQLException {
return this.resultSetType;
}
JDBC 2.0 Determine the result set type. |
public int getUpdateCount() throws SQLException {
if (this.results == null) {
return -1;
}
if (this.results.reallyResult()) {
return -1;
}
int truncatedUpdateCount = 0;
if (this.results.getUpdateCount() > Integer.MAX_VALUE) {
truncatedUpdateCount = Integer.MAX_VALUE;
} else {
truncatedUpdateCount = (int) this.results.getUpdateCount();
}
return truncatedUpdateCount;
}
getUpdateCount returns the current result as an update count, if the
result is a ResultSet or there are no more results, -1 is returned. It
should only be called once per result. |
public SQLWarning getWarnings() throws SQLException {
checkClosed();
if (this.connection != null && !this.connection.isClosed()
&& this.connection.versionMeetsMinimum(4, 1, 0)) {
SQLWarning pendingWarningsFromServer = SQLError
.convertShowWarningsToSQLWarnings(this.connection);
if (this.warningChain != null) {
this.warningChain.setNextWarning(pendingWarningsFromServer);
} else {
this.warningChain = pendingWarningsFromServer;
}
return this.warningChain;
}
return this.warningChain;
}
The first warning reported by calls on this Statement is returned. A
Statement's execute methods clear its java.sql.SQLWarning chain.
Subsequent Statement warnings will be chained to this
java.sql.SQLWarning.
The Warning chain is automatically cleared each time a statement is
(re)executed.
Note: If you are processing a ResultSet then any warnings
associated with ResultSet reads will be chained on the ResultSet object.
|
protected SQLException handleExceptionForBatch(int endOfBatchIndex,
int numValuesPerBatch,
int[] updateCounts,
SQLException ex) throws BatchUpdateException {
SQLException sqlEx;
for (int j = endOfBatchIndex; j > endOfBatchIndex - numValuesPerBatch; j--) {
updateCounts[j] = EXECUTE_FAILED;
}
if (this.continueBatchOnError &&
!(ex instanceof MySQLTimeoutException) &&
!(ex instanceof MySQLStatementCancelledException) &&
!hasDeadlockOrTimeoutRolledBackTx(ex)) {
sqlEx = ex;
} else {
int[] newUpdateCounts = new int[endOfBatchIndex];
System.arraycopy(updateCounts, 0,
newUpdateCounts, 0, endOfBatchIndex);
throw new java.sql.BatchUpdateException(ex
.getMessage(), ex.getSQLState(), ex
.getErrorCode(), newUpdateCounts);
}
return sqlEx;
}
|
protected final boolean hasDeadlockOrTimeoutRolledBackTx(SQLException ex) {
int vendorCode = ex.getErrorCode();
switch (vendorCode) {
case MysqlErrorNumbers.ER_LOCK_DEADLOCK:
case MysqlErrorNumbers.ER_LOCK_TABLE_FULL:
return true;
case MysqlErrorNumbers.ER_LOCK_WAIT_TIMEOUT:
try {
return !this.connection.versionMeetsMinimum(5, 0, 13);
} catch (SQLException sqlEx) {
// won't actually be thrown in this case
return false;
}
default:
return false;
}
}
|
public synchronized boolean isClosed() throws SQLException {
return this.isClosed;
}
|
public boolean isPoolable() throws SQLException {
return this.isPoolable;
}
|
public boolean isWrapperFor(Class iface) throws SQLException {
checkClosed();
// This works for classes that aren't actually wrapping
// anything
return iface.isInstance(this);
}
Returns true if this either implements the interface argument or is directly or indirectly a wrapper
for an object that does. Returns false otherwise. If this implements the interface then return true,
else if this is a wrapper then return the result of recursively calling isWrapperFor on the wrapped
object. If this does not implement the interface and is not a wrapper, return false.
This method should be implemented as a low-cost operation compared to unwrap so that
callers can use this method to avoid expensive unwrap calls that may fail. If this method
returns true then calling unwrap with the same argument should succeed. |
protected int processMultiCountsAndKeys(StatementImpl batchedStatement,
int updateCountCounter,
int[] updateCounts) throws SQLException {
updateCounts[updateCountCounter++] = batchedStatement.getUpdateCount();
boolean doGenKeys = this.batchedGeneratedKeys != null;
byte[][] row = null;
if (doGenKeys) {
long generatedKey = batchedStatement.getLastInsertID();
row = new byte[1][];
row[0] = Long.toString(generatedKey).getBytes();
this.batchedGeneratedKeys.add(new ByteArrayRow(row, getExceptionInterceptor()));
}
while (batchedStatement.getMoreResults()
|| batchedStatement.getUpdateCount() != -1) {
updateCounts[updateCountCounter++] = batchedStatement.getUpdateCount();
if (doGenKeys) {
long generatedKey = batchedStatement.getLastInsertID();
row = new byte[1][];
row[0] = Long.toString(generatedKey).getBytes();
this.batchedGeneratedKeys.add(new ByteArrayRow(row, getExceptionInterceptor()));
}
}
return updateCountCounter;
}
|
protected synchronized void realClose(boolean calledExplicitly,
boolean closeOpenResults) throws SQLException {
if (this.isClosed) {
return;
}
if (this.useUsageAdvisor) {
if (!calledExplicitly) {
String message = Messages.getString("Statement.63") //$NON-NLS-1$
+ Messages.getString("Statement.64"); //$NON-NLS-1$
this.eventSink.consumeEvent(new ProfilerEvent(
ProfilerEvent.TYPE_WARN,
"", //$NON-NLS-1$
this.currentCatalog, this.connectionId, this.getId(),
-1, System.currentTimeMillis(), 0,
Constants.MILLIS_I18N, null, this.pointOfOrigin,
message));
}
}
if (closeOpenResults) {
closeOpenResults = !this.holdResultsOpenOverClose;
}
if (closeOpenResults) {
if (this.results != null) {
try {
this.results.close();
} catch (Exception ex) {
;
}
}
closeAllOpenResults();
}
if (this.connection != null) {
if (this.maxRowsChanged) {
this.connection.unsetMaxRows(this);
}
if (!this.connection.getDontTrackOpenResources()) {
this.connection.unregisterStatement(this);
}
}
this.isClosed = true;
this.results = null;
this.connection = null;
this.warningChain = null;
this.openResults = null;
this.batchedGeneratedKeys = null;
this.localInfileInputStream = null;
this.pingTarget = null;
}
Closes this statement, and frees resources. |
public synchronized void removeOpenResultSet(ResultSet rs) {
if (this.openResults != null) {
this.openResults.remove(rs);
}
}
|
protected synchronized void resetCancelledState() {
if (this.cancelTimeoutMutex == null) {
return;
}
synchronized (this.cancelTimeoutMutex) {
this.wasCancelled = false;
this.wasCancelledByTimeout = false;
}
}
|
public void setCursorName(String name) throws SQLException {
// No-op
}
|
public void setEscapeProcessing(boolean enable) throws SQLException {
this.doEscapeProcessing = enable;
}
If escape scanning is on (the default), the driver will do escape
substitution before sending the SQL to the database. |
public void setFetchDirection(int direction) throws SQLException {
switch (direction) {
case java.sql.ResultSet.FETCH_FORWARD:
case java.sql.ResultSet.FETCH_REVERSE:
case java.sql.ResultSet.FETCH_UNKNOWN:
break;
default:
throw SQLError.createSQLException(
Messages.getString("Statement.5"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$
}
}
JDBC 2.0 Give a hint as to the direction in which the rows in a result
set will be processed. The hint applies only to result sets created using
this Statement object. The default value is ResultSet.FETCH_FORWARD. |
public void setFetchSize(int rows) throws SQLException {
if (((rows < 0) && (rows != Integer.MIN_VALUE))
|| ((this.maxRows != 0) && (this.maxRows != -1) && (rows > this
.getMaxRows()))) {
throw SQLError.createSQLException(
Messages.getString("Statement.7"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$ //$NON-NLS-2$
}
this.fetchSize = rows;
}
JDBC 2.0 Give the JDBC driver a hint as to the number of rows that should
be fetched from the database when more rows are needed. The number of
rows specified only affects result sets created using this statement. If
the value specified is zero, then the hint is ignored. The default value
is zero. |
protected void setHoldResultsOpenOverClose(boolean holdResultsOpenOverClose) {
this.holdResultsOpenOverClose = holdResultsOpenOverClose;
}
|
public synchronized void setLocalInfileInputStream(InputStream stream) {
this.localInfileInputStream = stream;
}
|
public void setMaxFieldSize(int max) throws SQLException {
if (max < 0) {
throw SQLError.createSQLException(Messages
.getString("Statement.11"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$
}
int maxBuf = (this.connection != null) ? this.connection
.getMaxAllowedPacket() : MysqlIO.getMaxBuf();
if (max > maxBuf) {
throw SQLError.createSQLException(Messages.getString(
"Statement.13", //$NON-NLS-1$
new Object[] { Constants.longValueOf(maxBuf) }), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$
}
this.maxFieldSize = max;
}
|
public void setMaxRows(int max) throws SQLException {
if ((max > MysqlDefs.MAX_ROWS) || (max < 0)) {
throw SQLError
.createSQLException(
Messages.getString("Statement.15") + max //$NON-NLS-1$
+ " > " //$NON-NLS-1$ //$NON-NLS-2$
+ MysqlDefs.MAX_ROWS + ".", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$ //$NON-NLS-2$
}
if (max == 0) {
max = -1;
}
this.maxRows = max;
this.maxRowsChanged = true;
if (this.maxRows == -1) {
this.connection.unsetMaxRows(this);
this.maxRowsChanged = false;
} else {
// Most people don't use setMaxRows()
// so don't penalize them
// with the extra query it takes
// to do it efficiently unless we need
// to.
this.connection.maxRowsChanged(this);
}
}
Set the maximum number of rows |
public synchronized void setPingTarget(PingTarget pingTarget) {
this.pingTarget = pingTarget;
}
|
public void setPoolable(boolean poolable) throws SQLException {
this.isPoolable = poolable;
}
|
public void setQueryTimeout(int seconds) throws SQLException {
if (seconds < 0) {
throw SQLError.createSQLException(Messages
.getString("Statement.21"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); //$NON-NLS-1$
}
this.timeoutInMillis = seconds * 1000;
}
Sets the queryTimeout limit |
void setResultSetConcurrency(int concurrencyFlag) {
this.resultSetConcurrency = concurrencyFlag;
}
Sets the concurrency for result sets generated by this statement |
void setResultSetType(int typeFlag) {
this.resultSetType = typeFlag;
}
Sets the result set type for result sets generated by this statement |
public Object unwrap(Class iface) throws SQLException {
try {
// This works for classes that aren't actually wrapping
// anything
return Util.cast(iface, this);
} catch (ClassCastException cce) {
throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(),
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
}
Returns an object that implements the given interface to allow access to non-standard methods,
or standard methods not exposed by the proxy.
The result may be either the object found to implement the interface or a proxy for that object.
If the receiver implements the interface then that is the object. If the receiver is a wrapper
and the wrapped object implements the interface then that is the object. Otherwise the object is
the result of calling unwrap recursively on the wrapped object. If the receiver is not a
wrapper and does not implement the interface, then an SQLException is thrown. |