JDBC Type 4 driver for MySQL with X DevAPI support for document store operations
The fundamental JDBC 4.2 API for relational database access, including connection management, statement execution, and result processing. This documentation covers the core interfaces and classes for traditional JDBC database operations.
The MySQL JDBC driver implementation that registers with the DriverManager for connection creation.
package com.mysql.cj.jdbc;
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
public Driver() throws SQLException {
// Required constructor
}
}
public class NonRegisteringDriver implements java.sql.Driver {
public Connection connect(String url, Properties info) throws SQLException;
public boolean acceptsURL(String url) throws SQLException;
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException;
public int getMajorVersion();
public int getMinorVersion();
public boolean jdbcCompliant();
public Logger getParentLogger() throws SQLFeatureNotSupportedException;
}Usage:
// Driver is auto-registered via static initializer
// Simply use DriverManager to get connections
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb",
"user",
"password"
);Core connection interface with MySQL-specific extensions for transaction management and connection state.
package com.mysql.cj.jdbc;
import java.util.concurrent.locks.Lock;
public interface JdbcConnection extends java.sql.Connection, com.mysql.cj.MysqlConnection {
// Statement creation
Statement createStatement() throws SQLException;
Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException;
Statement createStatement(int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException;
PreparedStatement prepareStatement(String sql) throws SQLException;
PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException;
PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException;
PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException;
PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException;
PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException;
CallableStatement prepareCall(String sql) throws SQLException;
CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException;
CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException;
// MySQL-specific statement creation
PreparedStatement clientPrepareStatement(String sql) throws SQLException;
PreparedStatement clientPrepareStatement(String sql, int autoGeneratedKeys) throws SQLException;
PreparedStatement clientPrepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException;
PreparedStatement clientPrepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException;
PreparedStatement clientPrepareStatement(String sql, int[] autoGeneratedKeyIndexes)
throws SQLException;
PreparedStatement clientPrepareStatement(String sql, String[] autoGeneratedKeyColNames)
throws SQLException;
PreparedStatement serverPrepareStatement(String sql) throws SQLException;
PreparedStatement serverPrepareStatement(String sql, int autoGeneratedKeys) throws SQLException;
PreparedStatement serverPrepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException;
PreparedStatement serverPrepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException;
PreparedStatement serverPrepareStatement(String sql, int[] autoGeneratedKeyIndexes)
throws SQLException;
PreparedStatement serverPrepareStatement(String sql, String[] autoGeneratedKeyColNames)
throws SQLException;
// Transaction management
void setAutoCommit(boolean autoCommit) throws SQLException;
boolean getAutoCommit() throws SQLException;
void commit() throws SQLException;
void rollback() throws SQLException;
void rollback(Savepoint savepoint) throws SQLException;
// Savepoints
Savepoint setSavepoint() throws SQLException;
Savepoint setSavepoint(String name) throws SQLException;
void releaseSavepoint(Savepoint savepoint) throws SQLException;
// Transaction isolation
void setTransactionIsolation(int level) throws SQLException;
int getTransactionIsolation() throws SQLException;
// Connection state
void close() throws SQLException;
boolean isClosed() throws SQLException;
boolean isValid(int timeout) throws SQLException;
// Database selection
void setCatalog(String catalog) throws SQLException;
String getCatalog() throws SQLException;
void setSchema(String schema) throws SQLException;
String getSchema() throws SQLException;
// Read-only mode
void setReadOnly(boolean readOnly) throws SQLException;
boolean isReadOnly() throws SQLException;
// Warnings
SQLWarning getWarnings() throws SQLException;
void clearWarnings() throws SQLException;
// Metadata
DatabaseMetaData getMetaData() throws SQLException;
// Type mapping
Map<String, Class<?>> getTypeMap() throws SQLException;
void setTypeMap(Map<String, Class<?>> map) throws SQLException;
// Holdability
void setHoldability(int holdability) throws SQLException;
int getHoldability() throws SQLException;
// Network timeout
void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException;
int getNetworkTimeout() throws SQLException;
// Abort
void abort(Executor executor) throws SQLException;
// Client info
void setClientInfo(String name, String value) throws SQLClientInfoException;
void setClientInfo(Properties properties) throws SQLClientInfoException;
String getClientInfo(String name) throws SQLException;
Properties getClientInfo() throws SQLException;
// Native SQL
String nativeSQL(String sql) throws SQLException;
// CLOB and BLOB creation
Clob createClob() throws SQLException;
Blob createBlob() throws SQLException;
NClob createNClob() throws SQLException;
SQLXML createSQLXML() throws SQLException;
// Array and Struct creation
Array createArrayOf(String typeName, Object[] elements) throws SQLException;
Struct createStruct(String typeName, Object[] attributes) throws SQLException;
// MySQL-specific methods
void changeUser(String userName, String newPassword) throws SQLException;
void ping() throws SQLException;
boolean hasSameProperties(JdbcConnection c);
String getStatementComment();
void setStatementComment(String comment);
boolean lowerCaseTableNames();
void resetServerState() throws SQLException;
boolean isSourceConnection();
boolean isSameResource(JdbcConnection c);
void setDatabase(String dbName) throws SQLException;
String getDatabase();
void shutdownServer() throws SQLException;
void setFailedOver(boolean flag);
// Connection state and monitoring
int getActiveStatementCount();
long getIdleFor();
boolean isServerLocal() throws SQLException;
String getHost();
String getHostPortPair();
Lock getLock();
// XA transaction support
boolean isInGlobalTx();
void setInGlobalTx(boolean flag);
// Server configuration
int getAutoIncrementIncrement();
int getSessionMaxRows();
void setSessionMaxRows(int max) throws SQLException;
ServerVersion getServerVersion();
// Advanced connection features
void setProxy(JdbcConnection proxy);
boolean isProxySet();
void abortInternal() throws SQLException;
CachedResultSetMetaData getCachedMetaData(String sql);
String getCharacterSetMetadata();
java.sql.Statement getMetadataSafeStatement() throws SQLException;
List<QueryInterceptor> getQueryInterceptorsInstances();
void initializeSafeQueryInterceptors() throws SQLException;
void unSafeQueryInterceptors() throws SQLException;
void initializeResultsMetadataFromCache(String sql, CachedResultSetMetaData cachedMetaData,
ResultSetInternalMethods resultSet) throws SQLException;
ClientInfoProvider getClientInfoProviderImpl() throws SQLException;
// Multi-host connection support
JdbcConnection getMultiHostSafeProxy();
JdbcConnection getMultiHostParentProxy();
JdbcConnection getActiveMySQLConnection();
// Internal connection management
boolean storesLowerCaseTableName();
void throwConnectionClosedException() throws SQLException;
void registerStatement(JdbcStatement stmt);
void unregisterStatement(JdbcStatement stmt);
void recachePreparedStatement(JdbcPreparedStatement pstmt) throws SQLException;
void decachePreparedStatement(JdbcPreparedStatement pstmt) throws SQLException;
void setReadOnlyInternal(boolean readOnlyFlag) throws SQLException;
boolean isReadOnly(boolean useSessionStatus) throws SQLException;
void pingInternal(boolean checkForClosedConnection, int timeoutMillis) throws SQLException;
}
public class ConnectionImpl extends AbstractJdbcConnection implements JdbcConnection {
// Implementation of JdbcConnection interface
}Usage:
// Basic connection
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb?useSSL=false",
"user",
"password"
);
// Transaction management
conn.setAutoCommit(false);
try {
// Execute statements
Statement stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO users (name) VALUES ('Alice')");
stmt.executeUpdate("UPDATE accounts SET balance = balance - 100 WHERE user = 'Alice'");
conn.commit();
} catch (SQLException e) {
conn.rollback();
throw e;
}
// Connection validation
if (conn.isValid(5)) {
System.out.println("Connection is valid");
}
conn.close();Standard Statement interface for executing SQL queries.
package com.mysql.cj.jdbc;
public interface JdbcStatement extends java.sql.Statement {
// Query execution
ResultSet executeQuery(String sql) throws SQLException;
int executeUpdate(String sql) throws SQLException;
int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException;
int executeUpdate(String sql, int[] columnIndexes) throws SQLException;
int executeUpdate(String sql, String[] columnNames) throws SQLException;
boolean execute(String sql) throws SQLException;
boolean execute(String sql, int autoGeneratedKeys) throws SQLException;
boolean execute(String sql, int[] columnIndexes) throws SQLException;
boolean execute(String sql, String[] columnNames) throws SQLException;
// Result retrieval
ResultSet getResultSet() throws SQLException;
int getUpdateCount() throws SQLException;
boolean getMoreResults() throws SQLException;
boolean getMoreResults(int current) throws SQLException;
ResultSet getGeneratedKeys() throws SQLException;
// Batch operations
void addBatch(String sql) throws SQLException;
void clearBatch() throws SQLException;
int[] executeBatch() throws SQLException;
// Statement lifecycle
void close() throws SQLException;
boolean isClosed() throws SQLException;
void cancel() throws SQLException;
// Result set configuration
void setFetchDirection(int direction) throws SQLException;
int getFetchDirection() throws SQLException;
void setFetchSize(int rows) throws SQLException;
int getFetchSize() throws SQLException;
int getResultSetConcurrency() throws SQLException;
int getResultSetType() throws SQLException;
int getResultSetHoldability() throws SQLException;
// Query timeouts
void setQueryTimeout(int seconds) throws SQLException;
int getQueryTimeout() throws SQLException;
// Max rows and field size
void setMaxRows(int max) throws SQLException;
int getMaxRows() throws SQLException;
void setMaxFieldSize(int max) throws SQLException;
int getMaxFieldSize() throws SQLException;
// Warnings
SQLWarning getWarnings() throws SQLException;
void clearWarnings() throws SQLException;
// Cursor name
void setCursorName(String name) throws SQLException;
// Connection reference
Connection getConnection() throws SQLException;
// Poolability
void setPoolable(boolean poolable) throws SQLException;
boolean isPoolable() throws SQLException;
// Close on completion
void closeOnCompletion() throws SQLException;
boolean isCloseOnCompletion() throws SQLException;
// Escape processing
void setEscapeProcessing(boolean enable) throws SQLException;
// Large update counts
long getLargeUpdateCount() throws SQLException;
void setLargeMaxRows(long max) throws SQLException;
long getLargeMaxRows() throws SQLException;
long[] executeLargeBatch() throws SQLException;
long executeLargeUpdate(String sql) throws SQLException;
long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException;
long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException;
long executeLargeUpdate(String sql, String[] columnNames) throws SQLException;
// MySQL-specific methods
void enableStreamingResults() throws SQLException;
void disableStreamingResults() throws SQLException;
void setLocalInfileInputStream(InputStream stream);
InputStream getLocalInfileInputStream();
void setPingTarget(PingTarget pingTarget);
ExceptionInterceptor getExceptionInterceptor();
// Result set management
void notifyResultSetClose(ResultSetInternalMethods rs);
int getOpenResultSetCount();
void setHoldResultsOpenOverClose(boolean holdResultsOpenOverClose);
ResultSetInternalMethods getResultSetInternal();
// Query and attribute management
Query getQuery();
void setAttribute(String name, Object value);
void clearAttributes();
}
public class StatementImpl extends AbstractStatement implements JdbcStatement {
// Implementation of JdbcStatement interface
}Usage:
Statement stmt = conn.createStatement();
// Execute query
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
rs.close();
// Execute update
int rowsAffected = stmt.executeUpdate("UPDATE users SET active = 1 WHERE id = 5");
System.out.println("Rows updated: " + rowsAffected);
// Execute with auto-generated keys
stmt.executeUpdate(
"INSERT INTO users (name) VALUES ('Bob')",
Statement.RETURN_GENERATED_KEYS
);
ResultSet keys = stmt.getGeneratedKeys();
if (keys.next()) {
System.out.println("Generated ID: " + keys.getLong(1));
}
keys.close();
stmt.close();PreparedStatement interface for parameterized SQL execution with enhanced performance.
package com.mysql.cj.jdbc;
public interface JdbcPreparedStatement extends java.sql.PreparedStatement, JdbcStatement {
// Execution
ResultSet executeQuery() throws SQLException;
int executeUpdate() throws SQLException;
boolean execute() throws SQLException;
long executeLargeUpdate() throws SQLException;
// Parameter setting - numeric types
void setBoolean(int parameterIndex, boolean x) throws SQLException;
void setByte(int parameterIndex, byte x) throws SQLException;
void setShort(int parameterIndex, short x) throws SQLException;
void setInt(int parameterIndex, int x) throws SQLException;
void setLong(int parameterIndex, long x) throws SQLException;
void setFloat(int parameterIndex, float x) throws SQLException;
void setDouble(int parameterIndex, double x) throws SQLException;
void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException;
// Parameter setting - string and character types
void setString(int parameterIndex, String x) throws SQLException;
void setNString(int parameterIndex, String value) throws SQLException;
void setBytes(int parameterIndex, byte[] x) throws SQLException;
// Parameter setting - date and time types
void setDate(int parameterIndex, Date x) throws SQLException;
void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException;
void setTime(int parameterIndex, Time x) throws SQLException;
void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException;
void setTimestamp(int parameterIndex, Timestamp x) throws SQLException;
void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException;
// Parameter setting - streams
void setAsciiStream(int parameterIndex, InputStream x) throws SQLException;
void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException;
void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException;
void setBinaryStream(int parameterIndex, InputStream x) throws SQLException;
void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException;
void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException;
void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException;
void setCharacterStream(int parameterIndex, Reader reader) throws SQLException;
void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException;
void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException;
void setNCharacterStream(int parameterIndex, Reader value) throws SQLException;
void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException;
// Parameter setting - LOBs
void setBlob(int parameterIndex, Blob x) throws SQLException;
void setBlob(int parameterIndex, InputStream inputStream) throws SQLException;
void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException;
void setClob(int parameterIndex, Clob x) throws SQLException;
void setClob(int parameterIndex, Reader reader) throws SQLException;
void setClob(int parameterIndex, Reader reader, long length) throws SQLException;
void setNClob(int parameterIndex, NClob value) throws SQLException;
void setNClob(int parameterIndex, Reader reader) throws SQLException;
void setNClob(int parameterIndex, Reader reader, long length) throws SQLException;
// Parameter setting - other types
void setObject(int parameterIndex, Object x) throws SQLException;
void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException;
void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength)
throws SQLException;
void setNull(int parameterIndex, int sqlType) throws SQLException;
void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException;
void setRef(int parameterIndex, Ref x) throws SQLException;
void setArray(int parameterIndex, Array x) throws SQLException;
void setURL(int parameterIndex, URL x) throws SQLException;
void setRowId(int parameterIndex, RowId x) throws SQLException;
void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException;
// Parameter metadata
ParameterMetaData getParameterMetaData() throws SQLException;
// Batch operations
void addBatch() throws SQLException;
// Clear parameters
void clearParameters() throws SQLException;
// Metadata
ResultSetMetaData getMetaData() throws SQLException;
// MySQL-specific prepared statement methods
QueryBindings getQueryBindings();
byte[] getBytesRepresentation(int parameterIndex) throws SQLException;
QueryInfo getQueryInfo();
boolean isNull(int paramIndex) throws SQLException;
String getPreparedSql();
void setBytes(int parameterIndex, byte[] x, boolean escapeIfNeeded) throws SQLException;
void setBigInteger(int parameterIndex, BigInteger x) throws SQLException;
void setNull(int parameterIndex, MysqlType mysqlType) throws SQLException;
ParameterBindings getParameterBindings() throws SQLException;
}
public class ClientPreparedStatement extends StatementImpl implements JdbcPreparedStatement {
// Client-side prepared statement implementation
}
public class ServerPreparedStatement extends ClientPreparedStatement {
// Server-side prepared statement implementation
}Usage:
String sql = "SELECT * FROM users WHERE age > ? AND city = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
// Set parameters
pstmt.setInt(1, 18);
pstmt.setString(2, "New York");
// Execute query
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name") + " - " + rs.getInt("age"));
}
rs.close();
// Reuse with different parameters
pstmt.setInt(1, 25);
pstmt.setString(2, "Boston");
rs = pstmt.executeQuery();
// Process results...
rs.close();
pstmt.close();CallableStatement interface for executing stored procedures with input and output parameters.
package com.mysql.cj.jdbc;
public class CallableStatement extends PreparedStatement implements java.sql.CallableStatement {
// Register output parameters
void registerOutParameter(int parameterIndex, int sqlType) throws SQLException;
void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException;
void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException;
void registerOutParameter(String parameterName, int sqlType) throws SQLException;
void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException;
void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException;
// Retrieve output parameters - by index
boolean wasNull() throws SQLException;
String getString(int parameterIndex) throws SQLException;
boolean getBoolean(int parameterIndex) throws SQLException;
byte getByte(int parameterIndex) throws SQLException;
short getShort(int parameterIndex) throws SQLException;
int getInt(int parameterIndex) throws SQLException;
long getLong(int parameterIndex) throws SQLException;
float getFloat(int parameterIndex) throws SQLException;
double getDouble(int parameterIndex) throws SQLException;
BigDecimal getBigDecimal(int parameterIndex) throws SQLException;
BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException;
byte[] getBytes(int parameterIndex) throws SQLException;
Date getDate(int parameterIndex) throws SQLException;
Date getDate(int parameterIndex, Calendar cal) throws SQLException;
Time getTime(int parameterIndex) throws SQLException;
Time getTime(int parameterIndex, Calendar cal) throws SQLException;
Timestamp getTimestamp(int parameterIndex) throws SQLException;
Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException;
Object getObject(int parameterIndex) throws SQLException;
Object getObject(int parameterIndex, Map<String, Class<?>> map) throws SQLException;
Ref getRef(int parameterIndex) throws SQLException;
Blob getBlob(int parameterIndex) throws SQLException;
Clob getClob(int parameterIndex) throws SQLException;
Array getArray(int parameterIndex) throws SQLException;
URL getURL(int parameterIndex) throws SQLException;
RowId getRowId(int parameterIndex) throws SQLException;
NClob getNClob(int parameterIndex) throws SQLException;
SQLXML getSQLXML(int parameterIndex) throws SQLException;
String getNString(int parameterIndex) throws SQLException;
Reader getCharacterStream(int parameterIndex) throws SQLException;
Reader getNCharacterStream(int parameterIndex) throws SQLException;
// Retrieve output parameters - by name
String getString(String parameterName) throws SQLException;
boolean getBoolean(String parameterName) throws SQLException;
byte getByte(String parameterName) throws SQLException;
short getShort(String parameterName) throws SQLException;
int getInt(String parameterName) throws SQLException;
long getLong(String parameterName) throws SQLException;
float getFloat(String parameterName) throws SQLException;
double getDouble(String parameterName) throws SQLException;
BigDecimal getBigDecimal(String parameterName) throws SQLException;
byte[] getBytes(String parameterName) throws SQLException;
Date getDate(String parameterName) throws SQLException;
Date getDate(String parameterName, Calendar cal) throws SQLException;
Time getTime(String parameterName) throws SQLException;
Time getTime(String parameterName, Calendar cal) throws SQLException;
Timestamp getTimestamp(String parameterName) throws SQLException;
Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException;
Object getObject(String parameterName) throws SQLException;
Object getObject(String parameterName, Map<String, Class<?>> map) throws SQLException;
Ref getRef(String parameterName) throws SQLException;
Blob getBlob(String parameterName) throws SQLException;
Clob getClob(String parameterName) throws SQLException;
Array getArray(String parameterName) throws SQLException;
URL getURL(String parameterName) throws SQLException;
RowId getRowId(String parameterName) throws SQLException;
NClob getNClob(String parameterName) throws SQLException;
SQLXML getSQLXML(String parameterName) throws SQLException;
String getNString(String parameterName) throws SQLException;
Reader getCharacterStream(String parameterName) throws SQLException;
Reader getNCharacterStream(String parameterName) throws SQLException;
// Set input parameters - by name
void setBoolean(String parameterName, boolean x) throws SQLException;
void setByte(String parameterName, byte x) throws SQLException;
void setShort(String parameterName, short x) throws SQLException;
void setInt(String parameterName, int x) throws SQLException;
void setLong(String parameterName, long x) throws SQLException;
void setFloat(String parameterName, float x) throws SQLException;
void setDouble(String parameterName, double x) throws SQLException;
void setBigDecimal(String parameterName, BigDecimal x) throws SQLException;
void setString(String parameterName, String x) throws SQLException;
void setBytes(String parameterName, byte[] x) throws SQLException;
void setDate(String parameterName, Date x) throws SQLException;
void setDate(String parameterName, Date x, Calendar cal) throws SQLException;
void setTime(String parameterName, Time x) throws SQLException;
void setTime(String parameterName, Time x, Calendar cal) throws SQLException;
void setTimestamp(String parameterName, Timestamp x) throws SQLException;
void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException;
void setAsciiStream(String parameterName, InputStream x) throws SQLException;
void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException;
void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException;
void setBinaryStream(String parameterName, InputStream x) throws SQLException;
void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException;
void setBinaryStream(String parameterName, InputStream x, long length) throws SQLException;
void setCharacterStream(String parameterName, Reader reader) throws SQLException;
void setCharacterStream(String parameterName, Reader reader, int length) throws SQLException;
void setCharacterStream(String parameterName, Reader reader, long length) throws SQLException;
void setNCharacterStream(String parameterName, Reader value) throws SQLException;
void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException;
void setBlob(String parameterName, Blob x) throws SQLException;
void setBlob(String parameterName, InputStream inputStream) throws SQLException;
void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException;
void setClob(String parameterName, Clob x) throws SQLException;
void setClob(String parameterName, Reader reader) throws SQLException;
void setClob(String parameterName, Reader reader, long length) throws SQLException;
void setNClob(String parameterName, NClob value) throws SQLException;
void setNClob(String parameterName, Reader reader) throws SQLException;
void setNClob(String parameterName, Reader reader, long length) throws SQLException;
void setObject(String parameterName, Object x) throws SQLException;
void setObject(String parameterName, Object x, int targetSqlType) throws SQLException;
void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException;
void setNull(String parameterName, int sqlType) throws SQLException;
void setNull(String parameterName, int sqlType, String typeName) throws SQLException;
void setURL(String parameterName, URL val) throws SQLException;
void setRowId(String parameterName, RowId x) throws SQLException;
void setNString(String parameterName, String value) throws SQLException;
void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException;
}Usage:
// Call stored procedure with IN and OUT parameters
CallableStatement cstmt = conn.prepareCall("{call getUserStats(?, ?)}");
// Set IN parameter
cstmt.setInt(1, 123); // user_id
// Register OUT parameter
cstmt.registerOutParameter(2, Types.INTEGER); // total_orders
// Execute
cstmt.execute();
// Retrieve OUT parameter
int totalOrders = cstmt.getInt(2);
System.out.println("Total orders: " + totalOrders);
cstmt.close();ResultSet interface for navigating and retrieving query results.
package com.mysql.cj.jdbc.result;
public interface ResultSetInternalMethods extends java.sql.ResultSet {
// Cursor navigation
boolean next() throws SQLException;
boolean previous() throws SQLException;
boolean first() throws SQLException;
boolean last() throws SQLException;
boolean absolute(int row) throws SQLException;
boolean relative(int rows) throws SQLException;
void beforeFirst() throws SQLException;
void afterLast() throws SQLException;
// Cursor position checking
boolean isBeforeFirst() throws SQLException;
boolean isAfterLast() throws SQLException;
boolean isFirst() throws SQLException;
boolean isLast() throws SQLException;
int getRow() throws SQLException;
// Data retrieval - by column index
String getString(int columnIndex) throws SQLException;
boolean getBoolean(int columnIndex) throws SQLException;
byte getByte(int columnIndex) throws SQLException;
short getShort(int columnIndex) throws SQLException;
int getInt(int columnIndex) throws SQLException;
long getLong(int columnIndex) throws SQLException;
float getFloat(int columnIndex) throws SQLException;
double getDouble(int columnIndex) throws SQLException;
BigDecimal getBigDecimal(int columnIndex) throws SQLException;
BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException;
byte[] getBytes(int columnIndex) throws SQLException;
Date getDate(int columnIndex) throws SQLException;
Date getDate(int columnIndex, Calendar cal) throws SQLException;
Time getTime(int columnIndex) throws SQLException;
Time getTime(int columnIndex, Calendar cal) throws SQLException;
Timestamp getTimestamp(int columnIndex) throws SQLException;
Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException;
Object getObject(int columnIndex) throws SQLException;
Object getObject(int columnIndex, Map<String, Class<?>> map) throws SQLException;
InputStream getAsciiStream(int columnIndex) throws SQLException;
InputStream getBinaryStream(int columnIndex) throws SQLException;
InputStream getUnicodeStream(int columnIndex) throws SQLException;
Reader getCharacterStream(int columnIndex) throws SQLException;
Ref getRef(int columnIndex) throws SQLException;
Blob getBlob(int columnIndex) throws SQLException;
Clob getClob(int columnIndex) throws SQLException;
Array getArray(int columnIndex) throws SQLException;
URL getURL(int columnIndex) throws SQLException;
RowId getRowId(int columnIndex) throws SQLException;
NClob getNClob(int columnIndex) throws SQLException;
SQLXML getSQLXML(int columnIndex) throws SQLException;
String getNString(int columnIndex) throws SQLException;
Reader getNCharacterStream(int columnIndex) throws SQLException;
// Data retrieval - by column name
String getString(String columnLabel) throws SQLException;
boolean getBoolean(String columnLabel) throws SQLException;
byte getByte(String columnLabel) throws SQLException;
short getShort(String columnLabel) throws SQLException;
int getInt(String columnLabel) throws SQLException;
long getLong(String columnLabel) throws SQLException;
float getFloat(String columnLabel) throws SQLException;
double getDouble(String columnLabel) throws SQLException;
BigDecimal getBigDecimal(String columnLabel) throws SQLException;
BigDecimal getBigDecimal(String columnLabel, int scale) throws SQLException;
byte[] getBytes(String columnLabel) throws SQLException;
Date getDate(String columnLabel) throws SQLException;
Date getDate(String columnLabel, Calendar cal) throws SQLException;
Time getTime(String columnLabel) throws SQLException;
Time getTime(String columnLabel, Calendar cal) throws SQLException;
Timestamp getTimestamp(String columnLabel) throws SQLException;
Timestamp getTimestamp(String columnLabel, Calendar cal) throws SQLException;
Object getObject(String columnLabel) throws SQLException;
Object getObject(String columnLabel, Map<String, Class<?>> map) throws SQLException;
InputStream getAsciiStream(String columnLabel) throws SQLException;
InputStream getBinaryStream(String columnLabel) throws SQLException;
InputStream getUnicodeStream(String columnLabel) throws SQLException;
Reader getCharacterStream(String columnLabel) throws SQLException;
Ref getRef(String columnLabel) throws SQLException;
Blob getBlob(String columnLabel) throws SQLException;
Clob getClob(String columnLabel) throws SQLException;
Array getArray(String columnLabel) throws SQLException;
URL getURL(String columnLabel) throws SQLException;
RowId getRowId(String columnLabel) throws SQLException;
NClob getNClob(String columnLabel) throws SQLException;
SQLXML getSQLXML(String columnLabel) throws SQLException;
String getNString(String columnLabel) throws SQLException;
Reader getNCharacterStream(String columnLabel) throws SQLException;
// Null checking
boolean wasNull() throws SQLException;
// Result set metadata
ResultSetMetaData getMetaData() throws SQLException;
int findColumn(String columnLabel) throws SQLException;
// Warnings
SQLWarning getWarnings() throws SQLException;
void clearWarnings() throws SQLException;
// Cursor name
String getCursorName() throws SQLException;
// Statement reference
Statement getStatement() throws SQLException;
// Fetch configuration
void setFetchDirection(int direction) throws SQLException;
int getFetchDirection() throws SQLException;
void setFetchSize(int rows) throws SQLException;
int getFetchSize() throws SQLException;
// Result set type and concurrency
int getType() throws SQLException;
int getConcurrency() throws SQLException;
int getHoldability() throws SQLException;
// Lifecycle
void close() throws SQLException;
boolean isClosed() throws SQLException;
}
public class ResultSetImpl implements ResultSetInternalMethods {
// Standard result set implementation
}
public class UpdatableResultSet extends ResultSetImpl {
// Updatable result set with update methods
// Row updates - by column index
void updateNull(int columnIndex) throws SQLException;
void updateBoolean(int columnIndex, boolean x) throws SQLException;
void updateByte(int columnIndex, byte x) throws SQLException;
void updateShort(int columnIndex, short x) throws SQLException;
void updateInt(int columnIndex, int x) throws SQLException;
void updateLong(int columnIndex, long x) throws SQLException;
void updateFloat(int columnIndex, float x) throws SQLException;
void updateDouble(int columnIndex, double x) throws SQLException;
void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException;
void updateString(int columnIndex, String x) throws SQLException;
void updateBytes(int columnIndex, byte[] x) throws SQLException;
void updateDate(int columnIndex, Date x) throws SQLException;
void updateTime(int columnIndex, Time x) throws SQLException;
void updateTimestamp(int columnIndex, Timestamp x) throws SQLException;
void updateAsciiStream(int columnIndex, InputStream x) throws SQLException;
void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException;
void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException;
void updateBinaryStream(int columnIndex, InputStream x) throws SQLException;
void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException;
void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException;
void updateCharacterStream(int columnIndex, Reader x) throws SQLException;
void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException;
void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException;
void updateObject(int columnIndex, Object x) throws SQLException;
void updateObject(int columnIndex, Object x, int scaleOrLength) throws SQLException;
void updateRef(int columnIndex, Ref x) throws SQLException;
void updateBlob(int columnIndex, Blob x) throws SQLException;
void updateBlob(int columnIndex, InputStream inputStream) throws SQLException;
void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException;
void updateClob(int columnIndex, Clob x) throws SQLException;
void updateClob(int columnIndex, Reader reader) throws SQLException;
void updateClob(int columnIndex, Reader reader, long length) throws SQLException;
void updateArray(int columnIndex, Array x) throws SQLException;
void updateRowId(int columnIndex, RowId x) throws SQLException;
void updateNString(int columnIndex, String nString) throws SQLException;
void updateNClob(int columnIndex, NClob nClob) throws SQLException;
void updateNClob(int columnIndex, Reader reader) throws SQLException;
void updateNClob(int columnIndex, Reader reader, long length) throws SQLException;
void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException;
void updateNCharacterStream(int columnIndex, Reader x) throws SQLException;
void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException;
// Row updates - by column name
void updateNull(String columnLabel) throws SQLException;
void updateBoolean(String columnLabel, boolean x) throws SQLException;
void updateByte(String columnLabel, byte x) throws SQLException;
void updateShort(String columnLabel, short x) throws SQLException;
void updateInt(String columnLabel, int x) throws SQLException;
void updateLong(String columnLabel, long x) throws SQLException;
void updateFloat(String columnLabel, float x) throws SQLException;
void updateDouble(String columnLabel, double x) throws SQLException;
void updateBigDecimal(String columnLabel, BigDecimal x) throws SQLException;
void updateString(String columnLabel, String x) throws SQLException;
void updateBytes(String columnLabel, byte[] x) throws SQLException;
void updateDate(String columnLabel, Date x) throws SQLException;
void updateTime(String columnLabel, Time x) throws SQLException;
void updateTimestamp(String columnLabel, Timestamp x) throws SQLException;
void updateAsciiStream(String columnLabel, InputStream x) throws SQLException;
void updateAsciiStream(String columnLabel, InputStream x, int length) throws SQLException;
void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException;
void updateBinaryStream(String columnLabel, InputStream x) throws SQLException;
void updateBinaryStream(String columnLabel, InputStream x, int length) throws SQLException;
void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException;
void updateCharacterStream(String columnLabel, Reader reader) throws SQLException;
void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException;
void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException;
void updateObject(String columnLabel, Object x) throws SQLException;
void updateObject(String columnLabel, Object x, int scaleOrLength) throws SQLException;
void updateRef(String columnLabel, Ref x) throws SQLException;
void updateBlob(String columnLabel, Blob x) throws SQLException;
void updateBlob(String columnLabel, InputStream inputStream) throws SQLException;
void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException;
void updateClob(String columnLabel, Clob x) throws SQLException;
void updateClob(String columnLabel, Reader reader) throws SQLException;
void updateClob(String columnLabel, Reader reader, long length) throws SQLException;
void updateArray(String columnLabel, Array x) throws SQLException;
void updateRowId(String columnLabel, RowId x) throws SQLException;
void updateNString(String columnLabel, String nString) throws SQLException;
void updateNClob(String columnLabel, NClob nClob) throws SQLException;
void updateNClob(String columnLabel, Reader reader) throws SQLException;
void updateNClob(String columnLabel, Reader reader, long length) throws SQLException;
void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException;
void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException;
void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException;
// Row manipulation
void insertRow() throws SQLException;
void updateRow() throws SQLException;
void deleteRow() throws SQLException;
void refreshRow() throws SQLException;
void cancelRowUpdates() throws SQLException;
void moveToInsertRow() throws SQLException;
void moveToCurrentRow() throws SQLException;
boolean rowUpdated() throws SQLException;
boolean rowInserted() throws SQLException;
boolean rowDeleted() throws SQLException;
}Usage:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM users");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt(3); // by column index
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
rs.close();
stmt.close();Metadata about result set columns including names, types, and properties.
package com.mysql.cj.jdbc.result;
public class ResultSetMetaData implements java.sql.ResultSetMetaData {
// Column count
int getColumnCount() throws SQLException;
// Column naming
String getColumnName(int column) throws SQLException;
String getColumnLabel(int column) throws SQLException;
// Table information
String getTableName(int column) throws SQLException;
String getSchemaName(int column) throws SQLException;
String getCatalogName(int column) throws SQLException;
// Type information
int getColumnType(int column) throws SQLException;
String getColumnTypeName(int column) throws SQLException;
String getColumnClassName(int column) throws SQLException;
// Size and precision
int getColumnDisplaySize(int column) throws SQLException;
int getPrecision(int column) throws SQLException;
int getScale(int column) throws SQLException;
// Column properties
boolean isAutoIncrement(int column) throws SQLException;
boolean isCaseSensitive(int column) throws SQLException;
boolean isCurrency(int column) throws SQLException;
int isNullable(int column) throws SQLException;
boolean isSigned(int column) throws SQLException;
boolean isReadOnly(int column) throws SQLException;
boolean isWritable(int column) throws SQLException;
boolean isDefinitelyWritable(int column) throws SQLException;
boolean isSearchable(int column) throws SQLException;
}
public interface CachedResultSetMetaData extends ResultSetMetaData {
// Cached metadata interface
}
public class CachedResultSetMetaDataImpl implements CachedResultSetMetaData {
// Cached metadata implementation
}Usage:
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
System.out.println("Columns: " + columnCount);
for (int i = 1; i <= columnCount; i++) {
System.out.println("Column " + i + ":");
System.out.println(" Name: " + meta.getColumnName(i));
System.out.println(" Type: " + meta.getColumnTypeName(i));
System.out.println(" Size: " + meta.getColumnDisplaySize(i));
System.out.println(" Nullable: " + (meta.isNullable(i) == ResultSetMetaData.columnNullable));
}Comprehensive metadata about the database capabilities, schemas, tables, and columns.
package com.mysql.cj.jdbc;
public class DatabaseMetaData implements java.sql.DatabaseMetaData {
// Database product information
String getDatabaseProductName() throws SQLException;
String getDatabaseProductVersion() throws SQLException;
int getDatabaseMajorVersion() throws SQLException;
int getDatabaseMinorVersion() throws SQLException;
// Driver information
String getDriverName() throws SQLException;
String getDriverVersion() throws SQLException;
int getDriverMajorVersion();
int getDriverMinorVersion();
// JDBC version
int getJDBCMajorVersion() throws SQLException;
int getJDBCMinorVersion() throws SQLException;
// SQL support
boolean supportsTransactions() throws SQLException;
boolean supportsStoredProcedures() throws SQLException;
boolean supportsOuterJoins() throws SQLException;
boolean supportsFullOuterJoins() throws SQLException;
boolean supportsLimitedOuterJoins() throws SQLException;
boolean supportsSubqueriesInComparisons() throws SQLException;
boolean supportsSubqueriesInExists() throws SQLException;
boolean supportsSubqueriesInIns() throws SQLException;
boolean supportsSubqueriesInQuantifieds() throws SQLException;
boolean supportsCorrelatedSubqueries() throws SQLException;
boolean supportsUnion() throws SQLException;
boolean supportsUnionAll() throws SQLException;
// Transaction support
boolean supportsMultipleTransactions() throws SQLException;
boolean supportsTransactionIsolationLevel(int level) throws SQLException;
int getDefaultTransactionIsolation() throws SQLException;
boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException;
boolean supportsDataManipulationTransactionsOnly() throws SQLException;
boolean dataDefinitionCausesTransactionCommit() throws SQLException;
boolean dataDefinitionIgnoredInTransactions() throws SQLException;
// Result set support
boolean supportsResultSetType(int type) throws SQLException;
boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException;
boolean ownUpdatesAreVisible(int type) throws SQLException;
boolean ownDeletesAreVisible(int type) throws SQLException;
boolean ownInsertsAreVisible(int type) throws SQLException;
boolean othersUpdatesAreVisible(int type) throws SQLException;
boolean othersDeletesAreVisible(int type) throws SQLException;
boolean othersInsertsAreVisible(int type) throws SQLException;
boolean updatesAreDetected(int type) throws SQLException;
boolean deletesAreDetected(int type) throws SQLException;
boolean insertsAreDetected(int type) throws SQLException;
// Batch updates
boolean supportsBatchUpdates() throws SQLException;
// Savepoints
boolean supportsSavepoints() throws SQLException;
// Named parameters
boolean supportsNamedParameters() throws SQLException;
// Multiple open results
boolean supportsMultipleOpenResults() throws SQLException;
// Schema information
ResultSet getCatalogs() throws SQLException;
ResultSet getSchemas() throws SQLException;
ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException;
// Table information
ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern,
String[] types) throws SQLException;
ResultSet getTableTypes() throws SQLException;
// Column information
ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern,
String columnNamePattern) throws SQLException;
// Primary key information
ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException;
// Foreign key information
ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException;
ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException;
ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable,
String foreignCatalog, String foreignSchema, String foreignTable)
throws SQLException;
// Index information
ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique,
boolean approximate) throws SQLException;
// Procedure information
ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern)
throws SQLException;
ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern,
String columnNamePattern) throws SQLException;
// Function information
ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern)
throws SQLException;
ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern,
String columnNamePattern) throws SQLException;
// Type information
ResultSet getTypeInfo() throws SQLException;
ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types)
throws SQLException;
// Connection reference
Connection getConnection() throws SQLException;
// User information
String getUserName() throws SQLException;
// URL information
String getURL() throws SQLException;
// Nullability information
boolean supportsNonNullableColumns() throws SQLException;
int getMaxConnections() throws SQLException;
int getMaxStatements() throws SQLException;
// SQL keywords
String getSQLKeywords() throws SQLException;
String getNumericFunctions() throws SQLException;
String getStringFunctions() throws SQLException;
String getSystemFunctions() throws SQLException;
String getTimeDateFunctions() throws SQLException;
// Search string escape
String getSearchStringEscape() throws SQLException;
// Extra name characters
String getExtraNameCharacters() throws SQLException;
// Identifier quote string
String getIdentifierQuoteString() throws SQLException;
// Case sensitivity
boolean supportsMixedCaseIdentifiers() throws SQLException;
boolean storesUpperCaseIdentifiers() throws SQLException;
boolean storesLowerCaseIdentifiers() throws SQLException;
boolean storesMixedCaseIdentifiers() throws SQLException;
boolean supportsMixedCaseQuotedIdentifiers() throws SQLException;
boolean storesUpperCaseQuotedIdentifiers() throws SQLException;
boolean storesLowerCaseQuotedIdentifiers() throws SQLException;
boolean storesMixedCaseQuotedIdentifiers() throws SQLException;
}
public class DatabaseMetaDataUsingInfoSchema extends DatabaseMetaData {
// Implementation using INFORMATION_SCHEMA tables
}Usage:
DatabaseMetaData meta = conn.getMetaData();
System.out.println("Database: " + meta.getDatabaseProductName() +
" " + meta.getDatabaseProductVersion());
System.out.println("Driver: " + meta.getDriverName() +
" " + meta.getDriverVersion());
// List all tables
ResultSet tables = meta.getTables(null, null, "%", new String[]{"TABLE"});
while (tables.next()) {
String tableName = tables.getString("TABLE_NAME");
System.out.println("Table: " + tableName);
// Get columns for this table
ResultSet columns = meta.getColumns(null, null, tableName, "%");
while (columns.next()) {
String columnName = columns.getString("COLUMN_NAME");
String columnType = columns.getString("TYPE_NAME");
System.out.println(" Column: " + columnName + " (" + columnType + ")");
}
columns.close();
}
tables.close();DataSource implementation for obtaining connections in managed environments.
package com.mysql.cj.jdbc;
public class MysqlDataSource implements javax.sql.DataSource, java.io.Serializable {
// Connection retrieval
public Connection getConnection() throws SQLException;
public Connection getConnection(String username, String password) throws SQLException;
// Configuration properties
public void setURL(String url);
public String getURL();
public void setUrl(String url); // Alternative setter
public String getUrl(); // Alternative getter
public void setUser(String user);
public String getUser();
public void setPassword(String password);
public void setServerName(String serverName);
public String getServerName();
public void setPort(int port);
public int getPort();
public void setPortNumber(int port); // Alternative setter
public int getPortNumber(); // Alternative getter
public void setDatabaseName(String databaseName);
public String getDatabaseName();
public void setServerTimezone(String serverTimezone);
public String getServerTimezone();
public void setUseSSL(boolean useSSL);
public boolean getUseSSL();
public void setRequireSSL(boolean requireSSL);
public boolean getRequireSSL();
public void setVerifyServerCertificate(boolean verifyServerCertificate);
public boolean getVerifyServerCertificate();
public void setCharacterEncoding(String characterEncoding);
public String getCharacterEncoding();
public void setAutoReconnect(boolean autoReconnect);
public boolean getAutoReconnect();
public void setUseUnicode(boolean useUnicode);
public boolean getUseUnicode();
public void setProfileSQL(boolean profileSQL);
public boolean getProfileSQL();
public void setLogger(String logger);
public String getLogger();
public void setUseInformationSchema(boolean useInformationSchema);
public boolean getUseInformationSchema();
public void setZeroDateTimeBehavior(String zeroDateTimeBehavior);
public String getZeroDateTimeBehavior();
public void setCachePrepStmts(boolean cachePrepStmts);
public boolean getCachePrepStmts();
public void setPrepStmtCacheSize(int prepStmtCacheSize);
public int getPrepStmtCacheSize();
public void setPrepStmtCacheSqlLimit(int prepStmtCacheSqlLimit);
public int getPrepStmtCacheSqlLimit();
public void setRewriteBatchedStatements(boolean rewriteBatchedStatements);
public boolean getRewriteBatchedStatements();
// Timeout settings
public void setConnectTimeout(int connectTimeout);
public int getConnectTimeout();
public void setSocketTimeout(int socketTimeout);
public int getSocketTimeout();
// Logging
public PrintWriter getLogWriter() throws SQLException;
public void setLogWriter(PrintWriter out) throws SQLException;
public void setLoginTimeout(int seconds) throws SQLException;
public int getLoginTimeout() throws SQLException;
// Parent logger
public Logger getParentLogger() throws SQLFeatureNotSupportedException;
}
public class MysqlDataSourceFactory implements ObjectFactory {
// Factory for JNDI lookup
public Object getObjectInstance(Object refObj, Name name, Context nameCtx, Hashtable<?, ?> env)
throws Exception;
}Usage:
// Configure DataSource
MysqlDataSource ds = new MysqlDataSource();
ds.setURL("jdbc:mysql://localhost:3306/mydb");
ds.setUser("root");
ds.setPassword("password");
// Or configure via properties
ds.setServerName("localhost");
ds.setPort(3306);
ds.setDatabaseName("mydb");
ds.setUser("root");
ds.setPassword("password");
// Performance optimizations
ds.setCachePrepStmts(true);
ds.setPrepStmtCacheSize(250);
ds.setPrepStmtCacheSqlLimit(2048);
ds.setRewriteBatchedStatements(true);
// Get connection
Connection conn = ds.getConnection();
// Use connection...
conn.close();Support for Binary Large Objects (BLOB) and Character Large Objects (CLOB).
package com.mysql.cj.jdbc;
public class Blob implements java.sql.Blob {
// Constructor
public Blob(byte[] data);
// Length
long length() throws SQLException;
// Retrieve data
byte[] getBytes(long pos, int length) throws SQLException;
InputStream getBinaryStream() throws SQLException;
InputStream getBinaryStream(long pos, long length) throws SQLException;
// Find position
long position(byte[] pattern, long start) throws SQLException;
long position(java.sql.Blob pattern, long start) throws SQLException;
// Modify data
int setBytes(long pos, byte[] bytes) throws SQLException;
int setBytes(long pos, byte[] bytes, int offset, int len) throws SQLException;
OutputStream setBinaryStream(long pos) throws SQLException;
void truncate(long len) throws SQLException;
// Lifecycle
void free() throws SQLException;
}
public class Clob implements java.sql.Clob {
// Constructor
public Clob(String charData);
// Length
long length() throws SQLException;
// Retrieve data
String getSubString(long pos, int length) throws SQLException;
Reader getCharacterStream() throws SQLException;
Reader getCharacterStream(long pos, long length) throws SQLException;
InputStream getAsciiStream() throws SQLException;
// Find position
long position(String searchstr, long start) throws SQLException;
long position(java.sql.Clob searchstr, long start) throws SQLException;
// Modify data
int setString(long pos, String str) throws SQLException;
int setString(long pos, String str, int offset, int len) throws SQLException;
OutputStream setAsciiStream(long pos) throws SQLException;
Writer setCharacterStream(long pos) throws SQLException;
void truncate(long len) throws SQLException;
// Lifecycle
void free() throws SQLException;
}
public class NClob extends Clob implements java.sql.NClob {
// National Character Large Object
public NClob(String charData);
}
public class MysqlSQLXML implements java.sql.SQLXML {
// XML data support
void free() throws SQLException;
InputStream getBinaryStream() throws SQLException;
OutputStream setBinaryStream() throws SQLException;
Reader getCharacterStream() throws SQLException;
Writer setCharacterStream() throws SQLException;
String getString() throws SQLException;
void setString(String value) throws SQLException;
<T extends javax.xml.transform.Source> T getSource(Class<T> sourceClass) throws SQLException;
<T extends javax.xml.transform.Result> T setResult(Class<T> resultClass) throws SQLException;
}Usage:
// Writing a BLOB
PreparedStatement pstmt = conn.prepareStatement(
"INSERT INTO documents (name, content) VALUES (?, ?)"
);
pstmt.setString(1, "document.pdf");
byte[] fileData = Files.readAllBytes(Paths.get("document.pdf"));
Blob blob = new Blob(fileData);
pstmt.setBlob(2, blob);
pstmt.executeUpdate();
// Reading a BLOB
ResultSet rs = stmt.executeQuery("SELECT content FROM documents WHERE id = 1");
if (rs.next()) {
Blob docBlob = rs.getBlob("content");
byte[] data = docBlob.getBytes(1, (int) docBlob.length());
Files.write(Paths.get("output.pdf"), data);
docBlob.free();
}
// Writing a CLOB
Clob clob = new Clob("Large text content...");
pstmt.setClob(2, clob);
pstmt.executeUpdate();
// Reading a CLOB
Clob textClob = rs.getClob("description");
String text = textClob.getSubString(1, (int) textClob.length());Transaction savepoints for partial rollback within a transaction.
package com.mysql.cj.jdbc;
public class MysqlSavepoint implements java.sql.Savepoint {
// Named savepoint
public MysqlSavepoint(String name);
// Unnamed savepoint
public MysqlSavepoint();
// Savepoint identification
int getSavepointId() throws SQLException;
String getSavepointName() throws SQLException;
}Usage:
conn.setAutoCommit(false);
try {
stmt.executeUpdate("INSERT INTO accounts (name, balance) VALUES ('Alice', 1000)");
// Create savepoint
Savepoint sp1 = conn.setSavepoint("savepoint1");
stmt.executeUpdate("UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice'");
// Something goes wrong, rollback to savepoint
if (someCondition) {
conn.rollback(sp1);
}
stmt.executeUpdate("UPDATE accounts SET balance = balance + 50 WHERE name = 'Alice'");
conn.commit();
} catch (SQLException e) {
conn.rollback();
throw e;
}Metadata about prepared statement parameters.
package com.mysql.cj.jdbc;
public class MysqlParameterMetadata implements java.sql.ParameterMetaData {
// Constructor
public MysqlParameterMetadata(int parameterCount);
// Parameter count
int getParameterCount() throws SQLException;
// Parameter type information
int getParameterType(int param) throws SQLException;
String getParameterTypeName(int param) throws SQLException;
String getParameterClassName(int param) throws SQLException;
// Parameter mode
int getParameterMode(int param) throws SQLException;
// Nullability
int isNullable(int param) throws SQLException;
// Sign
boolean isSigned(int param) throws SQLException;
// Precision and scale
int getPrecision(int param) throws SQLException;
int getScale(int param) throws SQLException;
}Usage:
PreparedStatement pstmt = conn.prepareStatement(
"SELECT * FROM users WHERE age > ? AND city = ?"
);
ParameterMetaData paramMeta = pstmt.getParameterMetaData();
int paramCount = paramMeta.getParameterCount();
System.out.println("Parameter count: " + paramCount);
for (int i = 1; i <= paramCount; i++) {
System.out.println("Parameter " + i + ":");
System.out.println(" Type: " + paramMeta.getParameterTypeName(i));
System.out.println(" Class: " + paramMeta.getParameterClassName(i));
System.out.println(" Mode: " + paramMeta.getParameterMode(i));
}Mechanism for storing and retrieving client information in the database.
package com.mysql.cj.jdbc;
public interface ClientInfoProvider {
void initialize(Connection conn, Properties configurationProps) throws SQLException;
void destroy() throws SQLException;
Properties getClientInfo(Connection conn) throws SQLException;
String getClientInfo(Connection conn, String name) throws SQLException;
void setClientInfo(Connection conn, Properties properties) throws SQLClientInfoException;
void setClientInfo(Connection conn, String name, String value) throws SQLClientInfoException;
}
public class ClientInfoProviderSP implements ClientInfoProvider {
// Stored procedure-based implementation
public void initialize(Connection conn, Properties configurationProps) throws SQLException;
public void destroy() throws SQLException;
public Properties getClientInfo(Connection conn) throws SQLException;
public String getClientInfo(Connection conn, String name) throws SQLException;
public void setClientInfo(Connection conn, Properties properties) throws SQLClientInfoException;
public void setClientInfo(Connection conn, String name, String value) throws SQLClientInfoException;
}
public class CommentClientInfoProvider implements ClientInfoProvider {
// Comment-based implementation (prepends client info as SQL comments)
public void initialize(Connection conn, Properties configurationProps) throws SQLException;
public void destroy() throws SQLException;
public Properties getClientInfo(Connection conn) throws SQLException;
public String getClientInfo(Connection conn, String name) throws SQLException;
public void setClientInfo(Connection conn, Properties properties) throws SQLClientInfoException;
public void setClientInfo(Connection conn, String name, String value) throws SQLClientInfoException;
}Usage:
Connection conn = DriverManager.getConnection(url, props);
// Set client info
conn.setClientInfo("ApplicationName", "MyApp");
conn.setClientInfo("ClientUser", "john.doe");
// Get client info
String appName = conn.getClientInfo("ApplicationName");
Properties allClientInfo = conn.getClientInfo();Options for controlling connection close behavior.
package com.mysql.cj.jdbc;
public enum CloseOption {
IMPLICIT, // Close operation initiated internally by a clean up routine
FORCED, // A forced, hard close
ROLLBACK, // Allow rollback during the close operation
PROPAGATE, // Allow propagating the close operation to dependents and owner objects
NO_CACHE; // Does not allow caching the closing object
public boolean in(CloseOption... options);
public boolean notIn(CloseOption... options);
}These options are used by advanced connection management methods like doClose(Throwable cause, CloseOption... options) for fine-grained control over connection cleanup behavior.
Install with Tessl CLI
npx tessl i tessl/maven-com-mysql--mysql-connector-j