Method from com.mysql.jdbc.PreparedStatement Detail: |
public void addBatch() throws SQLException {
if (this.batchedArgs == null) {
this.batchedArgs = new ArrayList();
}
for (int i = 0; i < this.parameterValues.length; i++) {
checkAllParametersSet(this.parameterValues[i],
this.parameterStreams[i], i);
}
this.batchedArgs.add(new BatchParams(this.parameterValues,
this.parameterStreams, this.isStream, this.streamLengths,
this.isNull));
}
JDBC 2.0 Add a set of parameters to the batch. |
public synchronized void addBatch(String sql) throws SQLException {
this.batchHasPlainStatements = true;
super.addBatch(sql);
}
|
protected String asSql() throws SQLException {
return asSql(false);
}
|
protected String asSql(boolean quoteStreamsAndUnknowns) throws SQLException {
if (this.isClosed) {
return "statement has been closed, no further internal information available";
}
StringBuffer buf = new StringBuffer();
try {
int realParameterCount = this.parameterCount + getParameterIndexOffset();
Object batchArg = null;
if (batchCommandIndex != -1)
batchArg = batchedArgs.get(batchCommandIndex);
for (int i = 0; i < realParameterCount; ++i) {
if (this.charEncoding != null) {
buf.append(new String(this.staticSqlStrings[i],
this.charEncoding));
} else {
buf.append(new String(this.staticSqlStrings[i]));
}
byte val[] = null;
if (batchArg != null && batchArg instanceof String) {
buf.append((String)batchArg);
continue;
}
if (batchCommandIndex == -1)
val = parameterValues[i];
else
val = ((BatchParams)batchArg).parameterStrings[i];
boolean isStreamParam = false;
if (batchCommandIndex == -1)
isStreamParam = isStream[i];
else
isStreamParam = ((BatchParams)batchArg).isStream[i];
if ((val == null) && !isStreamParam) {
if (quoteStreamsAndUnknowns) {
buf.append("'");
}
buf.append("** NOT SPECIFIED **"); //$NON-NLS-1$
if (quoteStreamsAndUnknowns) {
buf.append("'");
}
} else if (isStreamParam) {
if (quoteStreamsAndUnknowns) {
buf.append("'");
}
buf.append("** STREAM DATA **"); //$NON-NLS-1$
if (quoteStreamsAndUnknowns) {
buf.append("'");
}
} else {
if (this.charConverter != null) {
buf.append(this.charConverter.toString(val));
} else {
if (this.charEncoding != null) {
buf.append(new String(val, this.charEncoding));
} else {
buf.append(StringUtils.toAsciiString(val));
}
}
}
}
if (this.charEncoding != null) {
buf.append(new String(
this.staticSqlStrings[this.parameterCount + getParameterIndexOffset()],
this.charEncoding));
} else {
buf
.append(StringUtils
.toAsciiString(this.staticSqlStrings[this.parameterCount + getParameterIndexOffset()]));
}
} catch (UnsupportedEncodingException uue) {
throw new RuntimeException(Messages
.getString("PreparedStatement.32") //$NON-NLS-1$
+ this.charEncoding
+ Messages.getString("PreparedStatement.33")); //$NON-NLS-1$
}
return buf.toString();
}
|
protected static boolean canRewrite(String sql,
boolean isOnDuplicateKeyUpdate,
int locationOfOnDuplicateKeyUpdate,
int statementStartPos) {
// Needs to be INSERT, can't have INSERT ... SELECT or
// INSERT ... ON DUPLICATE KEY UPDATE with an id=LAST_INSERT_ID(...)
boolean rewritableOdku = true;
if (isOnDuplicateKeyUpdate) {
int updateClausePos = StringUtils.indexOfIgnoreCase(
locationOfOnDuplicateKeyUpdate, sql, " UPDATE ");
if (updateClausePos != -1) {
rewritableOdku = StringUtils
.indexOfIgnoreCaseRespectMarker(updateClausePos,
sql, "LAST_INSERT_ID", "\"'`", "\"'`",
false) == -1;
}
}
return StringUtils
.startsWithIgnoreCaseAndWs(sql, "INSERT",
statementStartPos)
&& StringUtils.indexOfIgnoreCaseRespectMarker(
statementStartPos, sql, "SELECT", "\"'`",
"\"'`", false) == -1 && rewritableOdku;
}
|
public boolean canRewriteAsMultiValueInsertAtSqlLevel() throws SQLException {
return this.parseInfo.canRewriteAsMultiValueInsert;
}
|
protected boolean checkReadOnlySafeStatement() throws SQLException {
return ((!this.connection.isReadOnly()) || (this.firstCharOfStmt == 'S'));
}
Check to see if the statement is safe for read-only slaves after failover. |
public synchronized void clearBatch() throws SQLException {
this.batchHasPlainStatements = false;
super.clearBatch();
}
|
public synchronized void clearParameters() throws SQLException {
checkClosed();
for (int i = 0; i < this.parameterValues.length; i++) {
this.parameterValues[i] = null;
this.parameterStreams[i] = null;
this.isStream[i] = false;
this.isNull[i] = false;
this.parameterTypes[i] = Types.NULL;
}
}
In general, parameter values remain in force for repeated used of a
Statement. Setting a parameter value automatically clears its previous
value. However, in some cases, it is useful to immediately release the
resources used by the current parameter values; this can be done by
calling clearParameters |
public synchronized void close() throws SQLException {
realClose(true, true);
}
Closes this prepared statement and releases all resources. |
protected int computeBatchSize(int numBatchedArgs) throws SQLException {
long[] combinedValues = computeMaxParameterSetSizeAndBatchSize(numBatchedArgs);
long maxSizeOfParameterSet = combinedValues[0];
long sizeOfEntireBatch = combinedValues[1];
int maxAllowedPacket = this.connection.getMaxAllowedPacket();
if (sizeOfEntireBatch < maxAllowedPacket - this.originalSql.length()) {
return numBatchedArgs;
}
return (int)Math.max(1, (maxAllowedPacket - this.originalSql.length()) / maxSizeOfParameterSet);
}
Computes the optimum number of batched parameter lists to send
without overflowing max_allowed_packet. |
protected long[] computeMaxParameterSetSizeAndBatchSize(int numBatchedArgs) throws SQLException {
long sizeOfEntireBatch = 0;
long maxSizeOfParameterSet = 0;
for (int i = 0; i < numBatchedArgs; i++) {
BatchParams paramArg = (BatchParams) this.batchedArgs
.get(i);
boolean[] isNullBatch = paramArg.isNull;
boolean[] isStreamBatch = paramArg.isStream;
long sizeOfParameterSet = 0;
for (int j = 0; j < isNullBatch.length; j++) {
if (!isNullBatch[j]) {
if (isStreamBatch[j]) {
int streamLength = paramArg.streamLengths[j];
if (streamLength != -1) {
sizeOfParameterSet += streamLength * 2; // for safety in escaping
} else {
int paramLength = paramArg.parameterStrings[j].length;
sizeOfParameterSet += paramLength;
}
} else {
sizeOfParameterSet += paramArg.parameterStrings[j].length;
}
} else {
sizeOfParameterSet += 4; // for NULL literal in SQL
}
}
//
// Account for static part of values clause
// This is a little naiive, because the ?s will be replaced
// but it gives us some padding, and is less housekeeping
// to ignore them. We're looking for a "fuzzy" value here
// anyway
//
if (getValuesClause() != null) {
sizeOfParameterSet += getValuesClause().length() + 1;
} else {
sizeOfParameterSet += this.originalSql.length() + 1;
}
sizeOfEntireBatch += sizeOfParameterSet;
if (sizeOfParameterSet > maxSizeOfParameterSet) {
maxSizeOfParameterSet = sizeOfParameterSet;
}
}
return new long[] {maxSizeOfParameterSet, sizeOfEntireBatch};
}
Computes the maximum parameter set size, and entire batch size given
the number of arguments in the batch. |
protected boolean containsOnDuplicateKeyUpdateInSQL() {
return this.parseInfo.isOnDuplicateKeyUpdate;
}
|
public boolean execute() throws SQLException {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
if(!checkReadOnlySafeStatement()) {
throw SQLError.createSQLException(Messages.getString("PreparedStatement.20") //$NON-NLS-1$
+ Messages.getString("PreparedStatement.21"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
ResultSetInternalMethods rs = null;
CachedResultSetMetaData cachedMetadata = null;
synchronized (locallyScopedConn.getMutex()) {
lastQueryIsOnDupKeyUpdate = false;
if (retrieveGeneratedKeys)
lastQueryIsOnDupKeyUpdate = containsOnDuplicateKeyUpdateInSQL();
boolean doStreaming = createStreamingResultSet();
clearWarnings();
// 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());
}
this.batchedGeneratedKeys = null;
Buffer sendPacket = fillSendPacket();
String oldCatalog = null;
if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) {
oldCatalog = locallyScopedConn.getCatalog();
locallyScopedConn.setCatalog(this.currentCatalog);
}
//
// Check if we have cached metadata for this query...
//
if (locallyScopedConn.getCacheResultSetMetadata()) {
cachedMetadata = locallyScopedConn.getCachedMetaData(this.originalSql);
}
Field[] metadataFromCache = null;
if (cachedMetadata != null) {
metadataFromCache = cachedMetadata.fields;
}
boolean oldInfoMsgState = false;
if (this.retrieveGeneratedKeys) {
oldInfoMsgState = locallyScopedConn.isReadInfoMsgEnabled();
locallyScopedConn.setReadInfoMsgEnabled(true);
}
// 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).
//
// Only apply max_rows to selects
//
if (locallyScopedConn.useMaxRows()) {
int rowLimit = -1;
if (this.firstCharOfStmt == 'S') {
if (this.hasLimitClause) {
rowLimit = this.maxRows;
} else {
if (this.maxRows < = 0) {
executeSimpleNonQuery(locallyScopedConn,
"SET OPTION SQL_SELECT_LIMIT=DEFAULT");
} else {
executeSimpleNonQuery(locallyScopedConn,
"SET OPTION SQL_SELECT_LIMIT="
+ this.maxRows);
}
}
} else {
executeSimpleNonQuery(locallyScopedConn,
"SET OPTION SQL_SELECT_LIMIT=DEFAULT");
}
// Finally, execute the query
rs = executeInternal(rowLimit, sendPacket,
doStreaming,
(this.firstCharOfStmt == 'S'), metadataFromCache, false);
} else {
rs = executeInternal(-1, sendPacket,
doStreaming,
(this.firstCharOfStmt == 'S'), metadataFromCache, false);
}
if (cachedMetadata != null) {
locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql,
cachedMetadata, this.results);
} else {
if (rs.reallyResult() && locallyScopedConn.getCacheResultSetMetadata()) {
locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql,
null /* will be created */, rs);
}
}
if (this.retrieveGeneratedKeys) {
locallyScopedConn.setReadInfoMsgEnabled(oldInfoMsgState);
rs.setFirstCharOfQuery(this.firstCharOfStmt);
}
if (oldCatalog != null) {
locallyScopedConn.setCatalog(oldCatalog);
}
if (rs != null) {
this.lastInsertId = rs.getUpdateID();
this.results = rs;
}
}
return ((rs != null) && rs.reallyResult());
}
Some prepared statements return multiple results; the execute method
handles these complex statements as well as the simpler form of
statements handled by executeQuery and executeUpdate |
public int[] executeBatch() throws SQLException {
checkClosed();
if (this.connection.isReadOnly()) {
throw new SQLException(Messages.getString("PreparedStatement.25") //$NON-NLS-1$
+ Messages.getString("PreparedStatement.26"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
}
synchronized (this.connection.getMutex()) {
if (this.batchedArgs == null || this.batchedArgs.size() == 0) {
return new int[0];
}
// we timeout the entire batch, not individual statements
int batchTimeout = this.timeoutInMillis;
this.timeoutInMillis = 0;
resetCancelledState();
try {
clearWarnings();
if (!this.batchHasPlainStatements
&& this.connection.getRewriteBatchedStatements()) {
if (canRewriteAsMultiValueInsertAtSqlLevel()) {
return executeBatchedInserts(batchTimeout);
}
if (this.connection.versionMeetsMinimum(4, 1, 0)
&& !this.batchHasPlainStatements
&& this.batchedArgs != null
&& this.batchedArgs.size() > 3 /* cost of option setting rt-wise */) {
return executePreparedBatchAsMultiStatement(batchTimeout);
}
}
return executeBatchSerially(batchTimeout);
} finally {
clearBatch();
}
}
}
JDBC 2.0 Submit a batch of commands to the database for execution. This
method is optional. |
protected int[] executeBatchSerially(int batchTimeout) throws SQLException {
ConnectionImpl locallyScopedConn = this.connection;
if (locallyScopedConn == null) {
checkClosed();
}
int[] updateCounts = null;
if (this.batchedArgs != null) {
int nbrCommands = this.batchedArgs.size();
updateCounts = new int[nbrCommands];
for (int i = 0; i < nbrCommands; i++) {
updateCounts[i] = -3;
}
SQLException sqlEx = null;
CancelTask timeoutTask = null;
try {
if (locallyScopedConn.getEnableQueryTimeouts() &&
batchTimeout != 0
&& locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
timeoutTask = new CancelTask(this);
locallyScopedConn.getCancelTimer().schedule(timeoutTask,
batchTimeout);
}
if (this.retrieveGeneratedKeys) {
this.batchedGeneratedKeys = new ArrayList(nbrCommands);
}
for (batchCommandIndex = 0; batchCommandIndex < nbrCommands; batchCommandIndex++) {
Object arg = this.batchedArgs.get(batchCommandIndex);
if (arg instanceof String) {
updateCounts[batchCommandIndex] = executeUpdate((String) arg);
} else {
BatchParams paramArg = (BatchParams) arg;
try {
updateCounts[batchCommandIndex] = executeUpdate(
paramArg.parameterStrings,
paramArg.parameterStreams, paramArg.isStream,
paramArg.streamLengths, paramArg.isNull, true);
if (this.retrieveGeneratedKeys) {
java.sql.ResultSet rs = null;
try {
if (containsOnDuplicateKeyUpdateInSQL())
rs = getGeneratedKeysInternal(1);
else
rs = getGeneratedKeysInternal();
while (rs.next()) {
this.batchedGeneratedKeys
.add(new ByteArrayRow(new byte[][] { rs.getBytes(1) }, getExceptionInterceptor()));
}
} finally {
if (rs != null) {
rs.close();
}
}
}
} catch (SQLException ex) {
updateCounts[batchCommandIndex] = EXECUTE_FAILED;
if (this.continueBatchOnError &&
!(ex instanceof MySQLTimeoutException) &&
!(ex instanceof MySQLStatementCancelledException) &&
!hasDeadlockOrTimeoutRolledBackTx(ex)) {
sqlEx = ex;
} else {
int[] newUpdateCounts = new int[batchCommandIndex];
System.arraycopy(updateCounts, 0,
newUpdateCounts, 0, batchCommandIndex);
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);
}
} catch (NullPointerException npe) {
try {
checkClosed();
} catch (SQLException connectionClosedEx) {
updateCounts[batchCommandIndex] = EXECUTE_FAILED;
int[] newUpdateCounts = new int[batchCommandIndex];
System.arraycopy(updateCounts, 0,
newUpdateCounts, 0, batchCommandIndex);
throw new java.sql.BatchUpdateException(connectionClosedEx
.getMessage(), connectionClosedEx.getSQLState(), connectionClosedEx
.getErrorCode(), newUpdateCounts);
}
throw npe; // we don't know why this happened, punt
} finally {
batchCommandIndex = -1;
if (timeoutTask != null) {
timeoutTask.cancel();
}
resetCancelledState();
}
}
return (updateCounts != null) ? updateCounts : new int[0];
}
Executes the current batch of statements by executing them one-by-one. |
protected int[] executeBatchedInserts(int batchTimeout) throws SQLException {
String valuesClause = getValuesClause();
ConnectionImpl locallyScopedConn = this.connection;
if (valuesClause == null) {
return executeBatchSerially(batchTimeout);
}
int numBatchedArgs = this.batchedArgs.size();
if (this.retrieveGeneratedKeys) {
this.batchedGeneratedKeys = new ArrayList(numBatchedArgs);
}
int numValuesPerBatch = computeBatchSize(numBatchedArgs);
if (numBatchedArgs < numValuesPerBatch) {
numValuesPerBatch = numBatchedArgs;
}
java.sql.PreparedStatement batchedStatement = null;
int batchedParamIndex = 1;
int updateCountRunningTotal = 0;
int numberToExecuteAsMultiValue = 0;
int batchCounter = 0;
CancelTask timeoutTask = null;
SQLException sqlEx = null;
int[] updateCounts = new int[numBatchedArgs];
for (int i = 0; i < this.batchedArgs.size(); i++) {
updateCounts[i] = 1;
}
try {
try {
batchedStatement = /* FIXME -if we ever care about folks proxying our ConnectionImpl */
prepareBatchedInsertSQL((ConnectionImpl) locallyScopedConn, numValuesPerBatch);
if (locallyScopedConn.getEnableQueryTimeouts()
&& batchTimeout != 0
&& locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
timeoutTask = new CancelTask(
(StatementImpl) batchedStatement);
locallyScopedConn.getCancelTimer().schedule(timeoutTask,
batchTimeout);
}
if (numBatchedArgs < numValuesPerBatch) {
numberToExecuteAsMultiValue = numBatchedArgs;
} else {
numberToExecuteAsMultiValue = numBatchedArgs
/ numValuesPerBatch;
}
int numberArgsToExecute = numberToExecuteAsMultiValue
* numValuesPerBatch;
for (int i = 0; i < numberArgsToExecute; i++) {
if (i != 0 && i % numValuesPerBatch == 0) {
try {
updateCountRunningTotal += batchedStatement
.executeUpdate();
} catch (SQLException ex) {
sqlEx = handleExceptionForBatch(batchCounter - 1,
numValuesPerBatch, updateCounts, ex);
}
getBatchedGeneratedKeys(batchedStatement);
batchedStatement.clearParameters();
batchedParamIndex = 1;
}
batchedParamIndex = setOneBatchedParameterSet(
batchedStatement, batchedParamIndex,
this.batchedArgs.get(batchCounter++));
}
try {
updateCountRunningTotal += batchedStatement.executeUpdate();
} catch (SQLException ex) {
sqlEx = handleExceptionForBatch(batchCounter - 1,
numValuesPerBatch, updateCounts, ex);
}
getBatchedGeneratedKeys(batchedStatement);
numValuesPerBatch = numBatchedArgs - batchCounter;
} finally {
if (batchedStatement != null) {
batchedStatement.close();
}
}
try {
if (numValuesPerBatch > 0) {
batchedStatement =
prepareBatchedInsertSQL((ConnectionImpl) locallyScopedConn,
numValuesPerBatch);
if (timeoutTask != null) {
timeoutTask.toCancel = (StatementImpl) batchedStatement;
}
batchedParamIndex = 1;
while (batchCounter < numBatchedArgs) {
batchedParamIndex = setOneBatchedParameterSet(
batchedStatement, batchedParamIndex,
this.batchedArgs.get(batchCounter++));
}
try {
updateCountRunningTotal += batchedStatement.executeUpdate();
} catch (SQLException ex) {
sqlEx = handleExceptionForBatch(batchCounter - 1,
numValuesPerBatch, updateCounts, ex);
}
getBatchedGeneratedKeys(batchedStatement);
}
if (sqlEx != null) {
throw new java.sql.BatchUpdateException(sqlEx
.getMessage(), sqlEx.getSQLState(), sqlEx
.getErrorCode(), updateCounts);
}
return updateCounts;
} finally {
if (batchedStatement != null) {
batchedStatement.close();
}
}
} finally {
if (timeoutTask != null) {
timeoutTask.cancel();
}
resetCancelledState();
}
}
Rewrites the already prepared statement into a multi-value insert
statement of 'statementsPerBatch' values and executes the entire batch
using this new statement. |
protected ResultSetInternalMethods executeInternal(int maxRowsToRetrieve,
Buffer sendPacket,
boolean createStreamingResultSet,
boolean queryIsSelectOnly,
Field[] metadataFromCache,
boolean isBatch) throws SQLException {
try {
resetCancelledState();
ConnectionImpl locallyScopedConnection = this.connection;
this.numberOfExecutions++;
if (this.doPingInstead) {
doPingInstead();
return this.results;
}
ResultSetInternalMethods rs;
CancelTask timeoutTask = null;
try {
if (locallyScopedConnection.getEnableQueryTimeouts() &&
this.timeoutInMillis != 0
&& locallyScopedConnection.versionMeetsMinimum(5, 0, 0)) {
timeoutTask = new CancelTask(this);
locallyScopedConnection.getCancelTimer().schedule(timeoutTask,
this.timeoutInMillis);
}
rs = locallyScopedConnection.execSQL(this, null, maxRowsToRetrieve, sendPacket,
this.resultSetType, this.resultSetConcurrency,
createStreamingResultSet, this.currentCatalog,
metadataFromCache, isBatch);
if (timeoutTask != null) {
timeoutTask.cancel();
if (timeoutTask.caughtWhileCancelling != null) {
throw timeoutTask.caughtWhileCancelling;
}
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();
}
}
return rs;
} catch (NullPointerException npe) {
checkClosed(); // we can't synchronize ourselves against async connection-close
// due to deadlock issues, so this is the next best thing for
// this particular corner case.
throw npe;
}
}
Actually execute the prepared statement. This is here so server-side
PreparedStatements can re-use most of the code from this class. |
protected int[] executePreparedBatchAsMultiStatement(int batchTimeout) throws SQLException {
synchronized (this.connection.getMutex()) {
// This is kind of an abuse, but it gets the job done
if (this.batchedValuesClause == null) {
this.batchedValuesClause = this.originalSql + ";";
}
ConnectionImpl locallyScopedConn = this.connection;
boolean multiQueriesEnabled = locallyScopedConn.getAllowMultiQueries();
CancelTask timeoutTask = null;
try {
clearWarnings();
int numBatchedArgs = this.batchedArgs.size();
if (this.retrieveGeneratedKeys) {
this.batchedGeneratedKeys = new ArrayList(numBatchedArgs);
}
int numValuesPerBatch = computeBatchSize(numBatchedArgs);
if (numBatchedArgs < numValuesPerBatch) {
numValuesPerBatch = numBatchedArgs;
}
java.sql.PreparedStatement batchedStatement = null;
int batchedParamIndex = 1;
int numberToExecuteAsMultiValue = 0;
int batchCounter = 0;
int updateCountCounter = 0;
int[] updateCounts = new int[numBatchedArgs];
SQLException sqlEx = null;
try {
if (!multiQueriesEnabled) {
locallyScopedConn.getIO().enableMultiQueries();
}
if (this.retrieveGeneratedKeys) {
batchedStatement = locallyScopedConn.prepareStatement(
generateMultiStatementForBatch(numValuesPerBatch),
RETURN_GENERATED_KEYS);
} else {
batchedStatement = locallyScopedConn
.prepareStatement(generateMultiStatementForBatch(numValuesPerBatch));
}
if (locallyScopedConn.getEnableQueryTimeouts() &&
batchTimeout != 0
&& locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
timeoutTask = new CancelTask((StatementImpl)batchedStatement);
locallyScopedConn.getCancelTimer().schedule(timeoutTask,
batchTimeout);
}
if (numBatchedArgs < numValuesPerBatch) {
numberToExecuteAsMultiValue = numBatchedArgs;
} else {
numberToExecuteAsMultiValue = numBatchedArgs / numValuesPerBatch;
}
int numberArgsToExecute = numberToExecuteAsMultiValue * numValuesPerBatch;
for (int i = 0; i < numberArgsToExecute; i++) {
if (i != 0 && i % numValuesPerBatch == 0) {
try {
batchedStatement.execute();
} catch (SQLException ex) {
sqlEx = handleExceptionForBatch(batchCounter, numValuesPerBatch,
updateCounts, ex);
}
updateCountCounter = processMultiCountsAndKeys(
(StatementImpl)batchedStatement, updateCountCounter,
updateCounts);
batchedStatement.clearParameters();
batchedParamIndex = 1;
}
batchedParamIndex = setOneBatchedParameterSet(batchedStatement,
batchedParamIndex, this.batchedArgs
.get(batchCounter++));
}
try {
batchedStatement.execute();
} catch (SQLException ex) {
sqlEx = handleExceptionForBatch(batchCounter - 1, numValuesPerBatch,
updateCounts, ex);
}
updateCountCounter = processMultiCountsAndKeys(
(StatementImpl)batchedStatement, updateCountCounter,
updateCounts);
batchedStatement.clearParameters();
numValuesPerBatch = numBatchedArgs - batchCounter;
} finally {
if (batchedStatement != null) {
batchedStatement.close();
}
}
try {
if (numValuesPerBatch > 0) {
if (this.retrieveGeneratedKeys) {
batchedStatement = locallyScopedConn.prepareStatement(
generateMultiStatementForBatch(numValuesPerBatch),
RETURN_GENERATED_KEYS);
} else {
batchedStatement = locallyScopedConn.prepareStatement(
generateMultiStatementForBatch(numValuesPerBatch));
}
if (timeoutTask != null) {
timeoutTask.toCancel = (StatementImpl)batchedStatement;
}
batchedParamIndex = 1;
while (batchCounter < numBatchedArgs) {
batchedParamIndex = setOneBatchedParameterSet(batchedStatement,
batchedParamIndex, this.batchedArgs
.get(batchCounter++));
}
try {
batchedStatement.execute();
} catch (SQLException ex) {
sqlEx = handleExceptionForBatch(batchCounter - 1, numValuesPerBatch,
updateCounts, ex);
}
updateCountCounter = processMultiCountsAndKeys(
(StatementImpl)batchedStatement, updateCountCounter,
updateCounts);
batchedStatement.clearParameters();
}
if (timeoutTask != null) {
if (timeoutTask.caughtWhileCancelling != null) {
throw timeoutTask.caughtWhileCancelling;
}
timeoutTask.cancel();
timeoutTask = null;
}
if (sqlEx != null) {
throw new java.sql.BatchUpdateException(sqlEx
.getMessage(), sqlEx.getSQLState(), sqlEx
.getErrorCode(), updateCounts);
}
return updateCounts;
} finally {
if (batchedStatement != null) {
batchedStatement.close();
}
}
} finally {
if (timeoutTask != null) {
timeoutTask.cancel();
}
resetCancelledState();
if (!multiQueriesEnabled) {
locallyScopedConn.getIO().disableMultiQueries();
}
clearBatch();
}
}
}
Rewrites the already prepared statement into a multi-statement
query of 'statementsPerBatch' values and executes the entire batch
using this new statement. |
public ResultSet executeQuery() throws SQLException {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
checkForDml(this.originalSql, this.firstCharOfStmt);
CachedResultSetMetaData cachedMetadata = null;
// We need to execute this all together
// So synchronize on the Connection's mutex (because
// even queries going through there synchronize
// on the same mutex.
synchronized (locallyScopedConn.getMutex()) {
clearWarnings();
boolean doStreaming = createStreamingResultSet();
this.batchedGeneratedKeys = null;
// 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) {
java.sql.Statement stmt = null;
try {
stmt = this.connection.createStatement();
((com.mysql.jdbc.StatementImpl)stmt).executeSimpleNonQuery(this.connection, "SET net_write_timeout="
+ this.connection.getNetTimeoutForStreamingResults());
} finally {
if (stmt != null) {
stmt.close();
}
}
}
Buffer sendPacket = fillSendPacket();
if (this.results != null) {
if (!this.connection.getHoldResultsOpenOverStatementClose()) {
if (!this.holdResultsOpenOverClose) {
this.results.realClose(false);
}
}
}
String oldCatalog = null;
if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) {
oldCatalog = locallyScopedConn.getCatalog();
locallyScopedConn.setCatalog(this.currentCatalog);
}
//
// Check if we have cached metadata for this query...
//
if (locallyScopedConn.getCacheResultSetMetadata()) {
cachedMetadata = locallyScopedConn.getCachedMetaData(this.originalSql);
}
Field[] metadataFromCache = null;
if (cachedMetadata != null) {
metadataFromCache = cachedMetadata.fields;
}
if (locallyScopedConn.useMaxRows()) {
// 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 (this.hasLimitClause) {
this.results = executeInternal(this.maxRows, sendPacket,
createStreamingResultSet(), true,
metadataFromCache, false);
} 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 = executeInternal(-1, sendPacket,
doStreaming, true,
metadataFromCache, false);
if (oldCatalog != null) {
this.connection.setCatalog(oldCatalog);
}
}
} else {
this.results = executeInternal(-1, sendPacket,
doStreaming, true,
metadataFromCache, false);
}
if (oldCatalog != null) {
locallyScopedConn.setCatalog(oldCatalog);
}
if (cachedMetadata != null) {
locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql,
cachedMetadata, this.results);
} else {
if (locallyScopedConn.getCacheResultSetMetadata()) {
locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql,
null /* will be created */, this.results);
}
}
}
this.lastInsertId = this.results.getUpdateID();
return this.results;
}
A Prepared SQL query is executed and its ResultSet is returned |
public int executeUpdate() throws SQLException {
return executeUpdate(true, false);
}
Execute a SQL INSERT, UPDATE or DELETE statement. In addition, SQL
statements that return nothing such as SQL DDL statements can be
executed. |
protected int executeUpdate(boolean clearBatchedGeneratedKeysAndWarnings,
boolean isBatch) throws SQLException {
if (clearBatchedGeneratedKeysAndWarnings) {
clearWarnings();
this.batchedGeneratedKeys = null;
}
return executeUpdate(this.parameterValues, this.parameterStreams,
this.isStream, this.streamLengths, this.isNull, isBatch);
}
|
protected int executeUpdate(byte[][] batchedParameterStrings,
InputStream[] batchedParameterStreams,
boolean[] batchedIsStream,
int[] batchedStreamLengths,
boolean[] batchedIsNull,
boolean isReallyBatch) throws SQLException {
checkClosed();
ConnectionImpl locallyScopedConn = this.connection;
if (locallyScopedConn.isReadOnly()) {
throw SQLError.createSQLException(Messages.getString("PreparedStatement.34") //$NON-NLS-1$
+ Messages.getString("PreparedStatement.35"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
if ((this.firstCharOfStmt == 'S')
&& isSelectQuery()) { //$NON-NLS-1$
throw SQLError.createSQLException(Messages.getString("PreparedStatement.37"), //$NON-NLS-1$
"01S03", getExceptionInterceptor()); //$NON-NLS-1$
}
if (this.results != null) {
if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) {
this.results.realClose(false);
}
}
ResultSetInternalMethods rs = null;
// The checking and changing of catalogs
// must happen in sequence, so synchronize
// on the same mutex that _conn is using
synchronized (locallyScopedConn.getMutex()) {
Buffer sendPacket = fillSendPacket(batchedParameterStrings,
batchedParameterStreams, batchedIsStream,
batchedStreamLengths);
String oldCatalog = null;
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");
}
boolean oldInfoMsgState = false;
if (this.retrieveGeneratedKeys) {
oldInfoMsgState = locallyScopedConn.isReadInfoMsgEnabled();
locallyScopedConn.setReadInfoMsgEnabled(true);
}
rs = executeInternal(-1, sendPacket, false, false, null,
isReallyBatch);
if (this.retrieveGeneratedKeys) {
locallyScopedConn.setReadInfoMsgEnabled(oldInfoMsgState);
rs.setFirstCharOfQuery(this.firstCharOfStmt);
}
if (oldCatalog != null) {
locallyScopedConn.setCatalog(oldCatalog);
}
}
this.results = rs;
this.updateCount = rs.getUpdateCount();
if (containsOnDuplicateKeyUpdateInSQL() &&
this.compensateForOnDuplicateKeyUpdate) {
if (this.updateCount == 2 || this.updateCount == 0) {
this.updateCount = 1;
}
}
int truncatedUpdateCount = 0;
if (this.updateCount > Integer.MAX_VALUE) {
truncatedUpdateCount = Integer.MAX_VALUE;
} else {
truncatedUpdateCount = (int) this.updateCount;
}
this.lastInsertId = rs.getUpdateID();
return truncatedUpdateCount;
}
Added to allow batch-updates |
protected Buffer fillSendPacket() throws SQLException {
return fillSendPacket(this.parameterValues, this.parameterStreams,
this.isStream, this.streamLengths);
}
Creates the packet that contains the query to be sent to the server. |
protected Buffer fillSendPacket(byte[][] batchedParameterStrings,
InputStream[] batchedParameterStreams,
boolean[] batchedIsStream,
int[] batchedStreamLengths) throws SQLException {
Buffer sendPacket = this.connection.getIO().getSharedSendPacket();
sendPacket.clear();
sendPacket.writeByte((byte) MysqlDefs.QUERY);
boolean useStreamLengths = this.connection
.getUseStreamLengthsInPrepStmts();
//
// Try and get this allocation as close as possible
// for BLOBs
//
int ensurePacketSize = 0;
String statementComment = this.connection.getStatementComment();
byte[] commentAsBytes = null;
if (statementComment != null) {
if (this.charConverter != null) {
commentAsBytes = this.charConverter.toBytes(statementComment);
} else {
commentAsBytes = StringUtils.getBytes(statementComment, this.charConverter,
this.charEncoding, this.connection
.getServerCharacterEncoding(), this.connection
.parserKnowsUnicode(), getExceptionInterceptor());
}
ensurePacketSize += commentAsBytes.length;
ensurePacketSize += 6; // for /*[space] [space]*/
}
for (int i = 0; i < batchedParameterStrings.length; i++) {
if (batchedIsStream[i] && useStreamLengths) {
ensurePacketSize += batchedStreamLengths[i];
}
}
if (ensurePacketSize != 0) {
sendPacket.ensureCapacity(ensurePacketSize);
}
if (commentAsBytes != null) {
sendPacket.writeBytesNoNull(Constants.SLASH_STAR_SPACE_AS_BYTES);
sendPacket.writeBytesNoNull(commentAsBytes);
sendPacket.writeBytesNoNull(Constants.SPACE_STAR_SLASH_SPACE_AS_BYTES);
}
for (int i = 0; i < batchedParameterStrings.length; i++) {
checkAllParametersSet(batchedParameterStrings[i],
batchedParameterStreams[i], i);
sendPacket.writeBytesNoNull(this.staticSqlStrings[i]);
if (batchedIsStream[i]) {
streamToBytes(sendPacket, batchedParameterStreams[i], true,
batchedStreamLengths[i], useStreamLengths);
} else {
sendPacket.writeBytesNoNull(batchedParameterStrings[i]);
}
}
sendPacket
.writeBytesNoNull(this.staticSqlStrings[batchedParameterStrings.length]);
return sendPacket;
}
Creates the packet that contains the query to be sent to the server. |
public byte[] getBytesRepresentation(int parameterIndex) throws SQLException {
if (this.isStream[parameterIndex]) {
return streamToBytes(this.parameterStreams[parameterIndex], false,
this.streamLengths[parameterIndex], this.connection
.getUseStreamLengthsInPrepStmts());
}
byte[] parameterVal = this.parameterValues[parameterIndex];
if (parameterVal == null) {
return null;
}
if ((parameterVal[0] == '\'')
&& (parameterVal[parameterVal.length - 1] == '\'')) {
byte[] valNoQuotes = new byte[parameterVal.length - 2];
System.arraycopy(parameterVal, 1, valNoQuotes, 0,
parameterVal.length - 2);
return valNoQuotes;
}
return parameterVal;
}
|
protected byte[] getBytesRepresentationForBatch(int parameterIndex,
int commandIndex) throws SQLException {
Object batchedArg = batchedArgs.get(commandIndex);
if (batchedArg instanceof String) {
try {
return ((String)batchedArg).getBytes(charEncoding);
} catch (UnsupportedEncodingException uue) {
throw new RuntimeException(Messages
.getString("PreparedStatement.32") //$NON-NLS-1$
+ this.charEncoding
+ Messages.getString("PreparedStatement.33")); //$NON-NLS-1$
}
}
BatchParams params = (BatchParams)batchedArg;
if (params.isStream[parameterIndex])
return streamToBytes(params.parameterStreams[parameterIndex], false,
params.streamLengths[parameterIndex],
connection.getUseStreamLengthsInPrepStmts());
byte parameterVal[] = params.parameterStrings[parameterIndex];
if (parameterVal == null)
return null;
if ((parameterVal[0] == '\'')
&& (parameterVal[parameterVal.length - 1] == '\'')) {
byte[] valNoQuotes = new byte[parameterVal.length - 2];
System.arraycopy(parameterVal, 1, valNoQuotes, 0,
parameterVal.length - 2);
return valNoQuotes;
}
return parameterVal;
}
Get bytes representation for a parameter in a statement batch. |
protected static PreparedStatement getInstance(ConnectionImpl conn,
String catalog) throws SQLException {
if (!Util.isJdbc4()) {
return new PreparedStatement(conn, catalog);
}
return (PreparedStatement) Util.handleNewInstance(
JDBC_4_PSTMT_2_ARG_CTOR, new Object[] { conn, catalog }, conn.getExceptionInterceptor());
}
Creates a prepared statement 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. |
protected static PreparedStatement getInstance(ConnectionImpl conn,
String sql,
String catalog) throws SQLException {
if (!Util.isJdbc4()) {
return new PreparedStatement(conn, sql, catalog);
}
return (PreparedStatement) Util.handleNewInstance(
JDBC_4_PSTMT_3_ARG_CTOR, new Object[] { conn, sql, catalog }, conn.getExceptionInterceptor());
}
Creates a prepared statement 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. |
protected static PreparedStatement getInstance(ConnectionImpl conn,
String sql,
String catalog,
ParseInfo cachedParseInfo) throws SQLException {
if (!Util.isJdbc4()) {
return new PreparedStatement(conn, sql, catalog, cachedParseInfo);
}
return (PreparedStatement) Util.handleNewInstance(
JDBC_4_PSTMT_4_ARG_CTOR, new Object[] { conn, sql, catalog,
cachedParseInfo }, conn.getExceptionInterceptor());
}
Creates a prepared statement 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. |
protected int getLocationOfOnDuplicateKeyUpdate() {
return this.parseInfo.locationOfOnDuplicateKeyUpdate;
}
|
public ResultSetMetaData getMetaData() throws SQLException {
//
// We could just tack on a LIMIT 0 here no matter what the
// statement, and check if a result set was returned or not,
// but I'm not comfortable with that, myself, so we take
// the "safer" road, and only allow metadata for _actual_
// SELECTS (but not SHOWs).
//
// CALL's are trapped further up and you end up with a
// CallableStatement anyway.
//
if (!isSelectQuery()) {
return null;
}
PreparedStatement mdStmt = null;
java.sql.ResultSet mdRs = null;
if (this.pstmtResultMetaData == null) {
try {
mdStmt = new PreparedStatement(this.connection,
this.originalSql, this.currentCatalog, this.parseInfo);
mdStmt.setMaxRows(0);
int paramCount = this.parameterValues.length;
for (int i = 1; i < = paramCount; i++) {
mdStmt.setString(i, ""); //$NON-NLS-1$
}
boolean hadResults = mdStmt.execute();
if (hadResults) {
mdRs = mdStmt.getResultSet();
this.pstmtResultMetaData = mdRs.getMetaData();
} else {
this.pstmtResultMetaData = new ResultSetMetaData(
new Field[0],
this.connection.getUseOldAliasMetadataBehavior(), getExceptionInterceptor());
}
} finally {
SQLException sqlExRethrow = null;
if (mdRs != null) {
try {
mdRs.close();
} catch (SQLException sqlEx) {
sqlExRethrow = sqlEx;
}
mdRs = null;
}
if (mdStmt != null) {
try {
mdStmt.close();
} catch (SQLException sqlEx) {
sqlExRethrow = sqlEx;
}
mdStmt = null;
}
if (sqlExRethrow != null) {
throw sqlExRethrow;
}
}
}
return this.pstmtResultMetaData;
}
The number, types and properties of a ResultSet's columns are provided by
the getMetaData method. |
public String getNonRewrittenSql() {
int indexOfBatch = this.originalSql.indexOf(" of: ");
if (indexOfBatch != -1) {
return this.originalSql.substring(indexOfBatch + 5);
}
return this.originalSql;
}
|
public ParameterBindings getParameterBindings() throws SQLException {
return new EmulatedPreparedStatementBindings();
}
|
protected int getParameterIndexOffset() {
return 0;
}
For calling stored functions, this will be -1 as we don't really count
the first '?' parameter marker, it's only syntax, but JDBC counts it
as #1, otherwise it will return 0 |
public ParameterMetaData getParameterMetaData() throws SQLException {
if (this.parameterMetaData == null) {
if (this.connection.getGenerateSimpleParameterMetadata()) {
this.parameterMetaData = new MysqlParameterMetadata(this.parameterCount);
} else {
this.parameterMetaData = new MysqlParameterMetadata(
null, this.parameterCount, getExceptionInterceptor());
}
}
return this.parameterMetaData;
}
|
ParseInfo getParseInfo() {
return this.parseInfo;
}
|
public String getPreparedSql() {
if (this.rewrittenBatchSize == 0) {
return this.originalSql;
}
try {
return this.parseInfo.getSqlForBatch(this.parseInfo);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
|
public int getRewrittenBatchSize() {
return this.rewrittenBatchSize;
}
|
public int getUpdateCount() throws SQLException {
int count = super.getUpdateCount();
if (containsOnDuplicateKeyUpdateInSQL() &&
this.compensateForOnDuplicateKeyUpdate) {
if (count == 2 || count == 0) {
count = 1;
}
}
return count;
}
|
protected String getValuesClause() throws SQLException {
return this.parseInfo.valuesClause;
}
|
public synchronized boolean isClosed() throws SQLException {
return this.isClosed;
}
|
boolean isNull(int paramIndex) {
return this.isNull[paramIndex];
}
|
protected boolean isSelectQuery() {
return StringUtils.startsWithIgnoreCaseAndWs(
StringUtils.stripComments(this.originalSql,
"'\"", "'\"", true, false, true, true),
"SELECT");
}
|
protected PreparedStatement prepareBatchedInsertSQL(ConnectionImpl localConn,
int numBatches) throws SQLException {
PreparedStatement pstmt = new PreparedStatement(localConn, "Rewritten batch of: " + this.originalSql, this.currentCatalog, this.parseInfo.getParseInfoForBatch(numBatches));
pstmt.setRetrieveGeneratedKeys(this.retrieveGeneratedKeys);
pstmt.rewrittenBatchSize = numBatches;
return pstmt;
}
Returns a prepared statement for the number of batched parameters, used when re-writing batch INSERTs. |
protected static int readFully(Reader reader,
char[] buf,
int length) throws IOException {
int numCharsRead = 0;
while (numCharsRead < length) {
int count = reader.read(buf, numCharsRead, length - numCharsRead);
if (count < 0) {
break;
}
numCharsRead += count;
}
return numCharsRead;
}
Reads length bytes from reader into buf. Blocks until enough input is
available |
protected void realClose(boolean calledExplicitly,
boolean closeOpenResults) throws SQLException {
if (this.useUsageAdvisor) {
if (this.numberOfExecutions < = 1) {
String message = Messages.getString("PreparedStatement.43"); //$NON-NLS-1$
this.eventSink.consumeEvent(new ProfilerEvent(
ProfilerEvent.TYPE_WARN, "", this.currentCatalog, //$NON-NLS-1$
this.connectionId, this.getId(), -1, System
.currentTimeMillis(), 0, Constants.MILLIS_I18N,
null,
this.pointOfOrigin, message));
}
}
super.realClose(calledExplicitly, closeOpenResults);
this.dbmd = null;
this.originalSql = null;
this.staticSqlStrings = null;
this.parameterValues = null;
this.parameterStreams = null;
this.isStream = null;
this.streamLengths = null;
this.isNull = null;
this.streamConvertBuf = null;
this.parameterTypes = null;
}
Closes this statement, releasing all resources |
public void setArray(int i,
Array x) throws SQLException {
throw SQLError.notImplemented();
}
JDBC 2.0 Set an Array parameter. |
public void setAsciiStream(int parameterIndex,
InputStream x) throws SQLException {
setAsciiStream(parameterIndex, x, -1);
}
|
public void setAsciiStream(int parameterIndex,
InputStream x,
int length) throws SQLException {
if (x == null) {
setNull(parameterIndex, java.sql.Types.VARCHAR);
} else {
setBinaryStream(parameterIndex, x, length);
}
}
When a very large ASCII value is input to a LONGVARCHAR parameter, it may
be more practical to send it via a java.io.InputStream. JDBC will read
the data from the stream as needed, until it reaches end-of-file. The
JDBC driver will do any necessary conversion from ASCII to the database
char format.
Note: This stream object can either be a standard Java stream
object or your own subclass that implements the standard interface.
|
public void setAsciiStream(int parameterIndex,
InputStream x,
long length) throws SQLException {
setAsciiStream(parameterIndex, x, (int)length);
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.CLOB;
}
|
public void setBigDecimal(int parameterIndex,
BigDecimal x) throws SQLException {
if (x == null) {
setNull(parameterIndex, java.sql.Types.DECIMAL);
} else {
setInternal(parameterIndex, StringUtils
.fixDecimalExponent(StringUtils.consistentToString(x)));
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.DECIMAL;
}
}
Set a parameter to a java.math.BigDecimal value. The driver converts this
to a SQL NUMERIC value when it sends it to the database. |
public void setBinaryStream(int parameterIndex,
InputStream x) throws SQLException {
setBinaryStream(parameterIndex, x, -1);
}
|
public void setBinaryStream(int parameterIndex,
InputStream x,
int length) throws SQLException {
if (x == null) {
setNull(parameterIndex, java.sql.Types.BINARY);
} else {
int parameterIndexOffset = getParameterIndexOffset();
if ((parameterIndex < 1)
|| (parameterIndex > this.staticSqlStrings.length)) {
throw SQLError.createSQLException(
Messages.getString("PreparedStatement.2") //$NON-NLS-1$
+ parameterIndex
+ Messages.getString("PreparedStatement.3") + this.staticSqlStrings.length + Messages.getString("PreparedStatement.4"), //$NON-NLS-1$ //$NON-NLS-2$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
} else if (parameterIndexOffset == -1 && parameterIndex == 1) {
throw SQLError.createSQLException("Can't set IN parameter for return value of stored function call.",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
this.parameterStreams[parameterIndex - 1 + parameterIndexOffset] = x;
this.isStream[parameterIndex - 1 + parameterIndexOffset] = true;
this.streamLengths[parameterIndex - 1 + parameterIndexOffset] = length;
this.isNull[parameterIndex - 1 + parameterIndexOffset] = false;
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.BLOB;
}
}
When a very large binary value is input to a LONGVARBINARY parameter, it
may be more practical to send it via a java.io.InputStream. JDBC will
read the data from the stream as needed, until it reaches end-of-file.
Note: This stream object can either be a standard Java stream
object or your own subclass that implements the standard interface.
|
public void setBinaryStream(int parameterIndex,
InputStream x,
long length) throws SQLException {
setBinaryStream(parameterIndex, x, (int)length);
}
|
public void setBlob(int i,
Blob x) throws SQLException {
if (x == null) {
setNull(i, Types.BLOB);
} else {
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
bytesOut.write('\'');
escapeblockFast(x.getBytes(1, (int) x.length()), bytesOut, (int) x
.length());
bytesOut.write('\'');
setInternal(i, bytesOut.toByteArray());
this.parameterTypes[i - 1 + getParameterIndexOffset()] = Types.BLOB;
}
}
JDBC 2.0 Set a BLOB parameter. |
public void setBlob(int parameterIndex,
InputStream inputStream) throws SQLException {
setBinaryStream(parameterIndex, inputStream);
}
|
public void setBlob(int parameterIndex,
InputStream inputStream,
long length) throws SQLException {
setBinaryStream(parameterIndex, inputStream, (int)length);
}
|
public void setBoolean(int parameterIndex,
boolean x) throws SQLException {
if (this.useTrueBoolean) {
setInternal(parameterIndex, x ? "1" : "0"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
setInternal(parameterIndex, x ? "'t'" : "'f'"); //$NON-NLS-1$ //$NON-NLS-2$
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.BOOLEAN;
}
}
Set a parameter to a Java boolean value. The driver converts this to a
SQL BIT value when it sends it to the database. |
public void setByte(int parameterIndex,
byte x) throws SQLException {
setInternal(parameterIndex, String.valueOf(x));
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.TINYINT;
}
Set a parameter to a Java byte value. The driver converts this to a SQL
TINYINT value when it sends it to the database. |
public void setBytes(int parameterIndex,
byte[] x) throws SQLException {
setBytes(parameterIndex, x, true, true);
if (x != null) {
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.BINARY;
}
}
Set a parameter to a Java array of bytes. The driver converts this to a
SQL VARBINARY or LONGVARBINARY (depending on the argument's size relative
to the driver's limits on VARBINARYs) when it sends it to the database. |
protected void setBytes(int parameterIndex,
byte[] x,
boolean checkForIntroducer,
boolean escapeForMBChars) throws SQLException {
if (x == null) {
setNull(parameterIndex, java.sql.Types.BINARY);
} else {
String connectionEncoding = this.connection.getEncoding();
if (this.connection.isNoBackslashEscapesSet()
|| (escapeForMBChars
&& this.connection.getUseUnicode()
&& connectionEncoding != null
&& CharsetMapping.isMultibyteCharset(connectionEncoding))) {
// Send as hex
ByteArrayOutputStream bOut = new ByteArrayOutputStream(
(x.length * 2) + 3);
bOut.write('x');
bOut.write('\'');
for (int i = 0; i < x.length; i++) {
int lowBits = (x[i] & 0xff) / 16;
int highBits = (x[i] & 0xff) % 16;
bOut.write(HEX_DIGITS[lowBits]);
bOut.write(HEX_DIGITS[highBits]);
}
bOut.write('\'');
setInternal(parameterIndex, bOut.toByteArray());
return;
}
// escape them
int numBytes = x.length;
int pad = 2;
boolean needsIntroducer = checkForIntroducer
&& this.connection.versionMeetsMinimum(4, 1, 0);
if (needsIntroducer) {
pad += 7;
}
ByteArrayOutputStream bOut = new ByteArrayOutputStream(numBytes
+ pad);
if (needsIntroducer) {
bOut.write('_');
bOut.write('b');
bOut.write('i');
bOut.write('n');
bOut.write('a');
bOut.write('r');
bOut.write('y');
}
bOut.write('\'');
for (int i = 0; i < numBytes; ++i) {
byte b = x[i];
switch (b) {
case 0: /* Must be escaped for 'mysql' */
bOut.write('\\');
bOut.write('0');
break;
case '\n': /* Must be escaped for logs */
bOut.write('\\');
bOut.write('n');
break;
case '\r':
bOut.write('\\');
bOut.write('r');
break;
case '\\':
bOut.write('\\');
bOut.write('\\');
break;
case '\'':
bOut.write('\\');
bOut.write('\'');
break;
case '"': /* Better safe than sorry */
bOut.write('\\');
bOut.write('"');
break;
case '\032': /* This gives problems on Win32 */
bOut.write('\\');
bOut.write('Z');
break;
default:
bOut.write(b);
}
}
bOut.write('\'');
setInternal(parameterIndex, bOut.toByteArray());
}
}
|
protected void setBytesNoEscape(int parameterIndex,
byte[] parameterAsBytes) throws SQLException {
byte[] parameterWithQuotes = new byte[parameterAsBytes.length + 2];
parameterWithQuotes[0] = '\'';
System.arraycopy(parameterAsBytes, 0, parameterWithQuotes, 1,
parameterAsBytes.length);
parameterWithQuotes[parameterAsBytes.length + 1] = '\'';
setInternal(parameterIndex, parameterWithQuotes);
}
Used by updatable result sets for refreshRow() because the parameter has
already been escaped for updater or inserter prepared statements. |
protected void setBytesNoEscapeNoQuotes(int parameterIndex,
byte[] parameterAsBytes) throws SQLException {
setInternal(parameterIndex, parameterAsBytes);
}
|
public void setCharacterStream(int parameterIndex,
Reader reader) throws SQLException {
setCharacterStream(parameterIndex, reader, -1);
}
|
public void setCharacterStream(int parameterIndex,
Reader reader,
int length) throws SQLException {
try {
if (reader == null) {
setNull(parameterIndex, Types.LONGVARCHAR);
} else {
char[] c = null;
int len = 0;
boolean useLength = this.connection
.getUseStreamLengthsInPrepStmts();
String forcedEncoding = this.connection.getClobCharacterEncoding();
if (useLength && (length != -1)) {
c = new char[length];
int numCharsRead = readFully(reader, c, length); // blocks
// until
// all
// read
if (forcedEncoding == null) {
setString(parameterIndex, new String(c, 0, numCharsRead));
} else {
try {
setBytes(parameterIndex, new String(c,
0,
numCharsRead).getBytes(forcedEncoding));
} catch (UnsupportedEncodingException uee) {
throw SQLError.createSQLException("Unsupported character encoding " +
forcedEncoding, SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
}
} else {
c = new char[4096];
StringBuffer buf = new StringBuffer();
while ((len = reader.read(c)) != -1) {
buf.append(c, 0, len);
}
if (forcedEncoding == null) {
setString(parameterIndex, buf.toString());
} else {
try {
setBytes(parameterIndex,
buf.toString().getBytes(forcedEncoding));
} catch (UnsupportedEncodingException uee) {
throw SQLError.createSQLException("Unsupported character encoding " +
forcedEncoding, SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
}
}
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.CLOB;
}
} catch (java.io.IOException ioEx) {
throw SQLError.createSQLException(ioEx.toString(),
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
}
}
JDBC 2.0 When a very large UNICODE value is input to a LONGVARCHAR
parameter, it may be more practical to send it via a java.io.Reader. JDBC
will read the data from the stream as needed, until it reaches
end-of-file. The JDBC driver will do any necessary conversion from
UNICODE to the database char format.
Note: This stream object can either be a standard Java stream
object or your own subclass that implements the standard interface.
|
public void setCharacterStream(int parameterIndex,
Reader reader,
long length) throws SQLException {
setCharacterStream(parameterIndex, reader, (int)length);
}
|
public void setClob(int i,
Clob x) throws SQLException {
if (x == null) {
setNull(i, Types.CLOB);
} else {
String forcedEncoding = this.connection.getClobCharacterEncoding();
if (forcedEncoding == null) {
setString(i, x.getSubString(1L, (int) x.length()));
} else {
try {
setBytes(i, x.getSubString(1L,
(int)x.length()).getBytes(forcedEncoding));
} catch (UnsupportedEncodingException uee) {
throw SQLError.createSQLException("Unsupported character encoding " +
forcedEncoding, SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
}
this.parameterTypes[i - 1 + getParameterIndexOffset()] = Types.CLOB;
}
}
JDBC 2.0 Set a CLOB parameter. |
public void setClob(int parameterIndex,
Reader reader) throws SQLException {
setCharacterStream(parameterIndex, reader);
}
|
public void setClob(int parameterIndex,
Reader reader,
long length) throws SQLException {
setCharacterStream(parameterIndex, reader, length);
}
|
public void setDate(int parameterIndex,
Date x) throws SQLException {
setDate(parameterIndex, x, null);
}
Set a parameter to a java.sql.Date value. The driver converts this to a
SQL DATE value when it sends it to the database. |
public void setDate(int parameterIndex,
Date x,
Calendar cal) throws SQLException {
if (x == null) {
setNull(parameterIndex, java.sql.Types.DATE);
} else {
checkClosed();
if (!this.useLegacyDatetimeCode) {
newSetDateInternal(parameterIndex, x, cal);
} else {
// FIXME: Have instance version of this, problem as it's
// not thread-safe :(
SimpleDateFormat dateFormatter = new SimpleDateFormat(
"''yyyy-MM-dd''", Locale.US); //$NON-NLS-1$
setInternal(parameterIndex, dateFormatter.format(x));
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.DATE;
}
}
}
Set a parameter to a java.sql.Date value. The driver converts this to a
SQL DATE value when it sends it to the database. |
public void setDouble(int parameterIndex,
double x) throws SQLException {
if (!this.connection.getAllowNanAndInf()
&& (x == Double.POSITIVE_INFINITY
|| x == Double.NEGATIVE_INFINITY || Double.isNaN(x))) {
throw SQLError.createSQLException("'" + x
+ "' is not a valid numeric or approximate numeric value",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
setInternal(parameterIndex, StringUtils.fixDecimalExponent(String
.valueOf(x)));
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.DOUBLE;
}
Set a parameter to a Java double value. The driver converts this to a SQL
DOUBLE value when it sends it to the database |
public void setFloat(int parameterIndex,
float x) throws SQLException {
setInternal(parameterIndex, StringUtils.fixDecimalExponent(String
.valueOf(x)));
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.FLOAT;
}
Set a parameter to a Java float value. The driver converts this to a SQL
FLOAT value when it sends it to the database. |
public void setInt(int parameterIndex,
int x) throws SQLException {
setInternal(parameterIndex, String.valueOf(x));
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.INTEGER;
}
Set a parameter to a Java int value. The driver converts this to a SQL
INTEGER value when it sends it to the database. |
protected final void setInternal(int paramIndex,
byte[] val) throws SQLException {
if (this.isClosed) {
throw SQLError.createSQLException(Messages.getString("PreparedStatement.48"), //$NON-NLS-1$
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
int parameterIndexOffset = getParameterIndexOffset();
checkBounds(paramIndex, parameterIndexOffset);
this.isStream[paramIndex - 1 + parameterIndexOffset] = false;
this.isNull[paramIndex - 1 + parameterIndexOffset] = false;
this.parameterStreams[paramIndex - 1 + parameterIndexOffset] = null;
this.parameterValues[paramIndex - 1 + parameterIndexOffset] = val;
}
|
protected final void setInternal(int paramIndex,
String val) throws SQLException {
checkClosed();
byte[] parameterAsBytes = null;
if (this.charConverter != null) {
parameterAsBytes = this.charConverter.toBytes(val);
} else {
parameterAsBytes = StringUtils.getBytes(val, this.charConverter,
this.charEncoding, this.connection
.getServerCharacterEncoding(), this.connection
.parserKnowsUnicode(), getExceptionInterceptor());
}
setInternal(paramIndex, parameterAsBytes);
}
|
public void setLong(int parameterIndex,
long x) throws SQLException {
setInternal(parameterIndex, String.valueOf(x));
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.BIGINT;
}
Set a parameter to a Java long value. The driver converts this to a SQL
BIGINT value when it sends it to the database. |
public void setNCharacterStream(int parameterIndex,
Reader value) throws SQLException {
setNCharacterStream(parameterIndex, value, -1);
}
|
public void setNCharacterStream(int parameterIndex,
Reader reader,
long length) throws SQLException {
try {
if (reader == null) {
setNull(parameterIndex, java.sql.Types.LONGVARCHAR);
} else {
char[] c = null;
int len = 0;
boolean useLength = this.connection
.getUseStreamLengthsInPrepStmts();
// Ignore "clobCharacterEncoding" because utf8 should be used this time.
if (useLength && (length != -1)) {
c = new char[(int) length]; // can't take more than Integer.MAX_VALUE
int numCharsRead = readFully(reader, c, (int) length); // blocks
// until
// all
// read
setNString(parameterIndex, new String(c, 0, numCharsRead));
} else {
c = new char[4096];
StringBuffer buf = new StringBuffer();
while ((len = reader.read(c)) != -1) {
buf.append(c, 0, len);
}
setNString(parameterIndex, buf.toString());
}
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = 2011; /* Types.NCLOB */
}
} catch (java.io.IOException ioEx) {
throw SQLError.createSQLException(ioEx.toString(),
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
}
}
JDBC 2.0 When a very large UNICODE value is input to a LONGVARCHAR
parameter, it may be more practical to send it via a java.io.Reader. JDBC
will read the data from the stream as needed, until it reaches
end-of-file. The JDBC driver will do any necessary conversion from
UNICODE to the database char format.
Note: This stream object can either be a standard Java stream
object or your own subclass that implements the standard interface.
|
public void setNClob(int parameterIndex,
Reader reader) throws SQLException {
setNCharacterStream(parameterIndex, reader);
}
|
public void setNClob(int parameterIndex,
Reader reader,
long length) throws SQLException {
if (reader == null) {
setNull(parameterIndex, java.sql.Types.LONGVARCHAR);
} else {
setNCharacterStream(parameterIndex, reader, length);
}
}
JDBC 4.0 Set a NCLOB parameter. |
public void setNString(int parameterIndex,
String x) throws SQLException {
if (this.charEncoding.equalsIgnoreCase("UTF-8")
|| this.charEncoding.equalsIgnoreCase("utf8")) {
setString(parameterIndex, x);
return;
}
// if the passed string is null, then set this column to null
if (x == null) {
setNull(parameterIndex, java.sql.Types.CHAR);
} else {
int stringLength = x.length();
// Ignore sql_mode=NO_BACKSLASH_ESCAPES in current implementation.
// Add introducer _utf8 for NATIONAL CHARACTER
StringBuffer buf = new StringBuffer((int) (x.length() * 1.1 + 4));
buf.append("_utf8");
buf.append('\'');
//
// Note: buf.append(char) is _faster_ than
// appending in blocks, because the block
// append requires a System.arraycopy()....
// go figure...
//
for (int i = 0; i < stringLength; ++i) {
char c = x.charAt(i);
switch (c) {
case 0: /* Must be escaped for 'mysql' */
buf.append('\\');
buf.append('0');
break;
case '\n': /* Must be escaped for logs */
buf.append('\\');
buf.append('n');
break;
case '\r':
buf.append('\\');
buf.append('r');
break;
case '\\':
buf.append('\\');
buf.append('\\');
break;
case '\'':
buf.append('\\');
buf.append('\'');
break;
case '"': /* Better safe than sorry */
if (this.usingAnsiMode) {
buf.append('\\');
}
buf.append('"');
break;
case '\032': /* This gives problems on Win32 */
buf.append('\\');
buf.append('Z');
break;
default:
buf.append(c);
}
}
buf.append('\'');
String parameterAsString = buf.toString();
byte[] parameterAsBytes = null;
if (!this.isLoadDataQuery) {
parameterAsBytes = StringUtils.getBytes(parameterAsString,
this.connection.getCharsetConverter("UTF-8"), "UTF-8",
this.connection.getServerCharacterEncoding(),
this.connection.parserKnowsUnicode(), getExceptionInterceptor());
} else {
// Send with platform character encoding
parameterAsBytes = parameterAsString.getBytes();
}
setInternal(parameterIndex, parameterAsBytes);
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = -9; /* Types.NVARCHAR */
}
}
Set a parameter to a Java String value. The driver converts this to a SQL
VARCHAR or LONGVARCHAR value with introducer _utf8 (depending on the
arguments size relative to the driver's limits on VARCHARs) when it sends
it to the database. If charset is set as utf8, this method just call setString. |
public void setNull(int parameterIndex,
int sqlType) throws SQLException {
setInternal(parameterIndex, "null"); //$NON-NLS-1$
this.isNull[parameterIndex - 1 + getParameterIndexOffset()] = true;
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.NULL;
}
|
public void setNull(int parameterIndex,
int sqlType,
String arg) throws SQLException {
setNull(parameterIndex, sqlType);
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.NULL;
}
|
public void setObject(int parameterIndex,
Object parameterObj) throws SQLException {
if (parameterObj == null) {
setNull(parameterIndex, java.sql.Types.OTHER);
} else {
if (parameterObj instanceof Byte) {
setInt(parameterIndex, ((Byte) parameterObj).intValue());
} else if (parameterObj instanceof String) {
setString(parameterIndex, (String) parameterObj);
} else if (parameterObj instanceof BigDecimal) {
setBigDecimal(parameterIndex, (BigDecimal) parameterObj);
} else if (parameterObj instanceof Short) {
setShort(parameterIndex, ((Short) parameterObj).shortValue());
} else if (parameterObj instanceof Integer) {
setInt(parameterIndex, ((Integer) parameterObj).intValue());
} else if (parameterObj instanceof Long) {
setLong(parameterIndex, ((Long) parameterObj).longValue());
} else if (parameterObj instanceof Float) {
setFloat(parameterIndex, ((Float) parameterObj).floatValue());
} else if (parameterObj instanceof Double) {
setDouble(parameterIndex, ((Double) parameterObj).doubleValue());
} else if (parameterObj instanceof byte[]) {
setBytes(parameterIndex, (byte[]) parameterObj);
} else if (parameterObj instanceof java.sql.Date) {
setDate(parameterIndex, (java.sql.Date) parameterObj);
} else if (parameterObj instanceof Time) {
setTime(parameterIndex, (Time) parameterObj);
} else if (parameterObj instanceof Timestamp) {
setTimestamp(parameterIndex, (Timestamp) parameterObj);
} else if (parameterObj instanceof Boolean) {
setBoolean(parameterIndex, ((Boolean) parameterObj)
.booleanValue());
} else if (parameterObj instanceof InputStream) {
setBinaryStream(parameterIndex, (InputStream) parameterObj, -1);
} else if (parameterObj instanceof java.sql.Blob) {
setBlob(parameterIndex, (java.sql.Blob) parameterObj);
} else if (parameterObj instanceof java.sql.Clob) {
setClob(parameterIndex, (java.sql.Clob) parameterObj);
} else if (this.connection.getTreatUtilDateAsTimestamp() &&
parameterObj instanceof java.util.Date) {
setTimestamp(parameterIndex, new Timestamp(
((java.util.Date) parameterObj).getTime()));
} else if (parameterObj instanceof BigInteger) {
setString(parameterIndex, parameterObj.toString());
} else {
setSerializableObject(parameterIndex, parameterObj);
}
}
}
|
public void setObject(int parameterIndex,
Object parameterObj,
int targetSqlType) throws SQLException {
if (!(parameterObj instanceof BigDecimal)) {
setObject(parameterIndex, parameterObj, targetSqlType, 0);
} else {
setObject(parameterIndex, parameterObj, targetSqlType,
((BigDecimal)parameterObj).scale());
}
}
|
public void setObject(int parameterIndex,
Object parameterObj,
int targetSqlType,
int scale) throws SQLException {
if (parameterObj == null) {
setNull(parameterIndex, java.sql.Types.OTHER);
} else {
try {
switch (targetSqlType) {
case Types.BOOLEAN:
/*
From Table-B5 in the JDBC-3.0 Spec
T S I B R F D D N B B C V L
I M N I E L O E U I O H A O
N A T G A O U C M T O A R N
Y L E I L A B I E L R C G
I L G N T L M R E H V
N I E T E A I A A A
T N R L C N R R
T C
H
A
R
-----------------------------------
Boolean x x x x x x x x x x x x x x
*/
if (parameterObj instanceof Boolean) {
setBoolean(parameterIndex, ((Boolean)parameterObj).booleanValue());
break;
} else if (parameterObj instanceof String) {
setBoolean(parameterIndex, "true".equalsIgnoreCase((String)parameterObj) ||
!"0".equalsIgnoreCase((String)parameterObj));
break;
} else if (parameterObj instanceof Number) {
int intValue = ((Number)parameterObj).intValue();
setBoolean(parameterIndex, intValue != 0);
break;
} else {
throw SQLError.createSQLException("No conversion from " + parameterObj.getClass().getName() +
" to Types.BOOLEAN possible.", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
case Types.BIT:
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
case Types.BIGINT:
case Types.REAL:
case Types.FLOAT:
case Types.DOUBLE:
case Types.DECIMAL:
case Types.NUMERIC:
setNumericObject(parameterIndex, parameterObj, targetSqlType, scale);
break;
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
if (parameterObj instanceof BigDecimal) {
setString(
parameterIndex,
(StringUtils
.fixDecimalExponent(StringUtils
.consistentToString((BigDecimal) parameterObj))));
} else {
setString(parameterIndex, parameterObj.toString());
}
break;
case Types.CLOB:
if (parameterObj instanceof java.sql.Clob) {
setClob(parameterIndex, (java.sql.Clob) parameterObj);
} else {
setString(parameterIndex, parameterObj.toString());
}
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
case Types.BLOB:
if (parameterObj instanceof byte[]) {
setBytes(parameterIndex, (byte[]) parameterObj);
} else if (parameterObj instanceof java.sql.Blob) {
setBlob(parameterIndex, (java.sql.Blob) parameterObj);
} else {
setBytes(parameterIndex, StringUtils.getBytes(
parameterObj.toString(), this.charConverter,
this.charEncoding, this.connection
.getServerCharacterEncoding(),
this.connection.parserKnowsUnicode(), getExceptionInterceptor()));
}
break;
case Types.DATE:
case Types.TIMESTAMP:
java.util.Date parameterAsDate;
if (parameterObj instanceof String) {
ParsePosition pp = new ParsePosition(0);
java.text.DateFormat sdf = new java.text.SimpleDateFormat(
getDateTimePattern((String) parameterObj, false), Locale.US);
parameterAsDate = sdf.parse((String) parameterObj, pp);
} else {
parameterAsDate = (java.util.Date) parameterObj;
}
switch (targetSqlType) {
case Types.DATE:
if (parameterAsDate instanceof java.sql.Date) {
setDate(parameterIndex,
(java.sql.Date) parameterAsDate);
} else {
setDate(parameterIndex, new java.sql.Date(
parameterAsDate.getTime()));
}
break;
case Types.TIMESTAMP:
if (parameterAsDate instanceof java.sql.Timestamp) {
setTimestamp(parameterIndex,
(java.sql.Timestamp) parameterAsDate);
} else {
setTimestamp(parameterIndex,
new java.sql.Timestamp(parameterAsDate
.getTime()));
}
break;
}
break;
case Types.TIME:
if (parameterObj instanceof String) {
java.text.DateFormat sdf = new java.text.SimpleDateFormat(
getDateTimePattern((String) parameterObj, true), Locale.US);
setTime(parameterIndex, new java.sql.Time(sdf.parse(
(String) parameterObj).getTime()));
} else if (parameterObj instanceof Timestamp) {
Timestamp xT = (Timestamp) parameterObj;
setTime(parameterIndex, new java.sql.Time(xT.getTime()));
} else {
setTime(parameterIndex, (java.sql.Time) parameterObj);
}
break;
case Types.OTHER:
setSerializableObject(parameterIndex, parameterObj);
break;
default:
throw SQLError.createSQLException(Messages
.getString("PreparedStatement.16"), //$NON-NLS-1$
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
}
} catch (Exception ex) {
if (ex instanceof SQLException) {
throw (SQLException) ex;
}
SQLException sqlEx = SQLError.createSQLException(
Messages.getString("PreparedStatement.17") //$NON-NLS-1$
+ parameterObj.getClass().toString()
+ Messages.getString("PreparedStatement.18") //$NON-NLS-1$
+ ex.getClass().getName()
+ Messages.getString("PreparedStatement.19") + ex.getMessage(), //$NON-NLS-1$
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
sqlEx.initCause(ex);
throw sqlEx;
}
}
}
Set the value of a parameter using an object; use the java.lang
equivalent objects for integral values.
The given Java object will be converted to the targetSqlType before being
sent to the database.
note that this method may be used to pass database-specific abstract data
types. This is done by using a Driver-specific Java type and using a
targetSqlType of java.sql.Types.OTHER
|
protected int setOneBatchedParameterSet(PreparedStatement batchedStatement,
int batchedParamIndex,
Object paramSet) throws SQLException {
BatchParams paramArg = (BatchParams)paramSet;
boolean[] isNullBatch = paramArg.isNull;
boolean[] isStreamBatch = paramArg.isStream;
for (int j = 0; j < isNullBatch.length; j++) {
if (isNullBatch[j]) {
batchedStatement.setNull(batchedParamIndex++, Types.NULL);
} else {
if (isStreamBatch[j]) {
batchedStatement.setBinaryStream(batchedParamIndex++,
paramArg.parameterStreams[j],
paramArg.streamLengths[j]);
} else {
((com.mysql.jdbc.PreparedStatement) batchedStatement)
.setBytesNoEscapeNoQuotes(batchedParamIndex++,
paramArg.parameterStrings[j]);
}
}
}
return batchedParamIndex;
}
|
public void setRef(int i,
Ref x) throws SQLException {
throw SQLError.notImplemented();
}
JDBC 2.0 Set a REF(<structured-type>) parameter. |
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 |
protected void setRetrieveGeneratedKeys(boolean retrieveGeneratedKeys) {
this.retrieveGeneratedKeys = retrieveGeneratedKeys;
}
|
public void setShort(int parameterIndex,
short x) throws SQLException {
setInternal(parameterIndex, String.valueOf(x));
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.SMALLINT;
}
Set a parameter to a Java short value. The driver converts this to a SQL
SMALLINT value when it sends it to the database. |
public void setString(int parameterIndex,
String x) throws SQLException {
// if the passed string is null, then set this column to null
if (x == null) {
setNull(parameterIndex, Types.CHAR);
} else {
checkClosed();
int stringLength = x.length();
if (this.connection.isNoBackslashEscapesSet()) {
// Scan for any nasty chars
boolean needsHexEscape = isEscapeNeededForString(x,
stringLength);
if (!needsHexEscape) {
byte[] parameterAsBytes = null;
StringBuffer quotedString = new StringBuffer(x.length() + 2);
quotedString.append('\'');
quotedString.append(x);
quotedString.append('\'');
if (!this.isLoadDataQuery) {
parameterAsBytes = StringUtils.getBytes(quotedString.toString(),
this.charConverter, this.charEncoding,
this.connection.getServerCharacterEncoding(),
this.connection.parserKnowsUnicode(), getExceptionInterceptor());
} else {
// Send with platform character encoding
parameterAsBytes = quotedString.toString().getBytes();
}
setInternal(parameterIndex, parameterAsBytes);
} else {
byte[] parameterAsBytes = null;
if (!this.isLoadDataQuery) {
parameterAsBytes = StringUtils.getBytes(x,
this.charConverter, this.charEncoding,
this.connection.getServerCharacterEncoding(),
this.connection.parserKnowsUnicode(), getExceptionInterceptor());
} else {
// Send with platform character encoding
parameterAsBytes = x.getBytes();
}
setBytes(parameterIndex, parameterAsBytes);
}
return;
}
String parameterAsString = x;
boolean needsQuoted = true;
if (this.isLoadDataQuery || isEscapeNeededForString(x, stringLength)) {
needsQuoted = false; // saves an allocation later
StringBuffer buf = new StringBuffer((int) (x.length() * 1.1));
buf.append('\'');
//
// Note: buf.append(char) is _faster_ than
// appending in blocks, because the block
// append requires a System.arraycopy()....
// go figure...
//
for (int i = 0; i < stringLength; ++i) {
char c = x.charAt(i);
switch (c) {
case 0: /* Must be escaped for 'mysql' */
buf.append('\\');
buf.append('0');
break;
case '\n': /* Must be escaped for logs */
buf.append('\\');
buf.append('n');
break;
case '\r':
buf.append('\\');
buf.append('r');
break;
case '\\':
buf.append('\\');
buf.append('\\');
break;
case '\'':
buf.append('\\');
buf.append('\'');
break;
case '"': /* Better safe than sorry */
if (this.usingAnsiMode) {
buf.append('\\');
}
buf.append('"');
break;
case '\032': /* This gives problems on Win32 */
buf.append('\\');
buf.append('Z');
break;
case '\u00a5':
case '\u20a9':
// escape characters interpreted as backslash by mysql
if(charsetEncoder != null) {
CharBuffer cbuf = CharBuffer.allocate(1);
ByteBuffer bbuf = ByteBuffer.allocate(1);
cbuf.put(c);
cbuf.position(0);
charsetEncoder.encode(cbuf, bbuf, true);
if(bbuf.get(0) == '\\') {
buf.append('\\');
}
}
// fall through
default:
buf.append(c);
}
}
buf.append('\'');
parameterAsString = buf.toString();
}
byte[] parameterAsBytes = null;
if (!this.isLoadDataQuery) {
if (needsQuoted) {
parameterAsBytes = StringUtils.getBytesWrapped(parameterAsString,
'\'', '\'', this.charConverter, this.charEncoding, this.connection
.getServerCharacterEncoding(), this.connection
.parserKnowsUnicode(), getExceptionInterceptor());
} else {
parameterAsBytes = StringUtils.getBytes(parameterAsString,
this.charConverter, this.charEncoding, this.connection
.getServerCharacterEncoding(), this.connection
.parserKnowsUnicode(), getExceptionInterceptor());
}
} else {
// Send with platform character encoding
parameterAsBytes = parameterAsString.getBytes();
}
setInternal(parameterIndex, parameterAsBytes);
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.VARCHAR;
}
}
Set a parameter to a Java String value. The driver converts this to a SQL
VARCHAR or LONGVARCHAR value (depending on the arguments size relative to
the driver's limits on VARCHARs) when it sends it to the database. |
public void setTime(int parameterIndex,
Time x) throws SQLException {
setTimeInternal(parameterIndex, x, null, Util.getDefaultTimeZone(), false);
}
Set a parameter to a java.sql.Time value. The driver converts this to a
SQL TIME value when it sends it to the database. |
public void setTime(int parameterIndex,
Time x,
Calendar cal) throws SQLException {
setTimeInternal(parameterIndex, x, cal, cal.getTimeZone(), true);
}
Set a parameter to a java.sql.Time value. The driver converts this to a
SQL TIME value when it sends it to the database. |
public void setTimestamp(int parameterIndex,
Timestamp x) throws SQLException {
setTimestampInternal(parameterIndex, x, null, Util.getDefaultTimeZone(), false);
}
Set a parameter to a java.sql.Timestamp value. The driver converts this
to a SQL TIMESTAMP value when it sends it to the database. |
public void setTimestamp(int parameterIndex,
Timestamp x,
Calendar cal) throws SQLException {
setTimestampInternal(parameterIndex, x, cal, cal.getTimeZone(), true);
}
Set a parameter to a java.sql.Timestamp value. The driver converts this
to a SQL TIMESTAMP value when it sends it to the database. |
public void setURL(int parameterIndex,
URL arg) throws SQLException {
if (arg != null) {
setString(parameterIndex, arg.toString());
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.DATALINK;
} else {
setNull(parameterIndex, Types.CHAR);
}
}
|
public void setUnicodeStream(int parameterIndex,
InputStream x,
int length) throws SQLException {
if (x == null) {
setNull(parameterIndex, java.sql.Types.VARCHAR);
} else {
setBinaryStream(parameterIndex, x, length);
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.CLOB;
}
} Deprecated!
When a very large Unicode value is input to a LONGVARCHAR parameter, it
may be more practical to send it via a java.io.InputStream. JDBC will
read the data from the stream as needed, until it reaches end-of-file.
The JDBC driver will do any necessary conversion from UNICODE to the
database char format.
Note: This stream object can either be a standard Java stream
object or your own subclass that implements the standard interface.
|
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(super.toString());
buf.append(": "); //$NON-NLS-1$
try {
buf.append(asSql());
} catch (SQLException sqlEx) {
buf.append("EXCEPTION: " + sqlEx.toString());
}
return buf.toString();
}
Returns this PreparedStatement represented as a string. |