or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdconfiguration.mdexceptions.mdindex.mdinterceptors.mdjdbc-advanced.mdjdbc-core.mdjdbc-high-availability.mdlogging-monitoring.mdtype-system.mdutilities.mdxdevapi-core.mdxdevapi-crud.mdxdevapi-sql.md
tile.json

tessl/maven-com-mysql--mysql-connector-j

JDBC Type 4 driver for MySQL with X DevAPI support for document store operations

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/com.mysql/mysql-connector-j@9.2.x

To install, run

npx @tessl/cli install tessl/maven-com-mysql--mysql-connector-j@9.2.0

index.mddocs/

MySQL Connector/J

MySQL Connector/J is a pure Java JDBC Type 4 driver that implements the Java Database Connectivity (JDBC) 4.2 API and MySQL X DevAPI for connecting Java applications to MySQL databases. It provides comprehensive database connectivity through standard JDBC operations and supports MySQL's document store features through the X DevAPI for NoSQL-style CRUD operations.

Package Information

  • Package Name: mysql-connector-j
  • Maven Coordinates: com.mysql:mysql-connector-j:9.2.0
  • Package Type: Maven
  • Language: Java
  • Minimum Java Version: Java 8
  • Installation: Add to Maven pom.xml:
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>9.2.0</version>
</dependency>

For Gradle:

implementation 'com.mysql:mysql-connector-j:9.2.0'

Core Imports

JDBC API Imports

// Driver and connection
import com.mysql.cj.jdbc.Driver;
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

X DevAPI Imports

// Session and core interfaces
import com.mysql.cj.xdevapi.Session;
import com.mysql.cj.xdevapi.SessionFactory;
import com.mysql.cj.xdevapi.Client;
import com.mysql.cj.xdevapi.ClientFactory;
import com.mysql.cj.xdevapi.Schema;
import com.mysql.cj.xdevapi.Collection;
import com.mysql.cj.xdevapi.Table;
import com.mysql.cj.xdevapi.DbDoc;

IMPORTANT - Import Ambiguity Warning:

If you use both JDBC and X DevAPI in the same file, avoid wildcard imports (import java.sql.* and import com.mysql.cj.xdevapi.*) together, as they create an ambiguity for the Statement interface which exists in both packages:

  • java.sql.Statement (JDBC)
  • com.mysql.cj.xdevapi.Statement (X DevAPI)

Use explicit imports or fully qualified names when using both APIs:

// Option 1: Use explicit imports
import java.sql.Connection;
import java.sql.PreparedStatement;
import com.mysql.cj.xdevapi.Session;
import com.mysql.cj.xdevapi.FindStatement;

// Option 2: Use fully qualified names when necessary
java.sql.Statement jdbcStmt = conn.createStatement();
com.mysql.cj.xdevapi.Statement xStmt = session.sql("SELECT * FROM users");

Basic Usage

JDBC Connection Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/mydb";
        String user = "root";
        String password = "password";

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            // Execute a query
            String sql = "SELECT id, name FROM users WHERE age > ?";
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setInt(1, 18);

                try (ResultSet rs = pstmt.executeQuery()) {
                    while (rs.next()) {
                        int id = rs.getInt("id");
                        String name = rs.getString("name");
                        System.out.println("ID: " + id + ", Name: " + name);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

X DevAPI Session Example

import com.mysql.cj.xdevapi.*;

public class XDevApiExample {
    public static void main(String[] args) {
        // Create a session
        SessionFactory factory = new SessionFactory();
        String url = "mysqlx://root:password@localhost:33060/mydb";

        try (Session session = factory.getSession(url)) {
            // Get schema and collection
            Schema schema = session.getDefaultSchema();
            Collection collection = schema.getCollection("users");

            // Add a document using JSON string
            collection.add("{\"name\": \"John Doe\", \"age\": 30}").execute();

            // Find documents
            DocResult result = collection.find("age > :minAge")
                .bind("minAge", 18)
                .execute();

            while (result.hasNext()) {
                DbDoc user = result.next();
                System.out.println("User: " + user.toString());
            }
        }
    }
}

Architecture

MySQL Connector/J provides two distinct APIs for database access:

JDBC API Architecture

The traditional JDBC 4.2 implementation follows the standard Java database connectivity patterns:

  • Driver: Entry point via com.mysql.cj.jdbc.Driver registered with DriverManager
  • Connection: JdbcConnection interface provides MySQL-specific extensions to java.sql.Connection
  • Statement Types: Statement, PreparedStatement, CallableStatement for SQL execution
  • ResultSet: Standard result set implementation with scrollable and updatable variants
  • DataSource: Connection pooling support via MysqlDataSource, MysqlConnectionPoolDataSource, MysqlXADataSource
  • Metadata: Comprehensive database and result set metadata via DatabaseMetaData

X DevAPI Architecture

The modern document store API provides NoSQL-style operations:

  • Session Management: Session and Client interfaces for connection lifecycle
  • Schema Objects: Schema provides access to collections and tables
  • Collections: Document store operations via Collection interface
  • CRUD Builders: Fluent statement builders (AddStatement, FindStatement, ModifyStatement, RemoveStatement)
  • SQL Support: Direct SQL execution via SqlStatement within X DevAPI context
  • Result Types: Specialized results (DocResult, RowResult, SqlResult)

Key Components

  • Configuration: Connection URLs parsed by ConnectionUrl with properties managed by PropertySet
  • Protocol Layer: Low-level MySQL protocol implementation hidden behind public APIs
  • Authentication: Pluggable authentication via AuthenticationPlugin interface
  • Exception Hierarchy: CJException base with specific subtypes for different error conditions
  • Logging: Unified logging via Log interface with multiple implementations

Capabilities

JDBC Core Operations

The fundamental JDBC 4.2 API for relational database access, including connection management, statement execution, and result processing.

// Driver registration and connection
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    static {
        // Auto-registers with DriverManager
    }
}

// Connection interface
public interface JdbcConnection extends Connection, MysqlConnection {
    PreparedStatement clientPrepareStatement(String sql) throws SQLException;
    PreparedStatement serverPrepareStatement(String sql) throws SQLException;
    void setAutoCommit(boolean autoCommit) throws SQLException;
    void commit() throws SQLException;
    void rollback() throws SQLException;
}

// Statement execution
public interface JdbcStatement extends Statement {
    ResultSet executeQuery(String sql) throws SQLException;
    int executeUpdate(String sql) throws SQLException;
    boolean execute(String sql) throws SQLException;
}

// Prepared statement
public interface JdbcPreparedStatement extends PreparedStatement, JdbcStatement {
    void setInt(int parameterIndex, int x) throws SQLException;
    void setString(int parameterIndex, String x) throws SQLException;
    void setObject(int parameterIndex, Object x) throws SQLException;
    ResultSet executeQuery() throws SQLException;
    int executeUpdate() throws SQLException;
}

// DataSource for connection pooling
public class MysqlDataSource implements DataSource {
    public Connection getConnection() throws SQLException;
    public Connection getConnection(String username, String password) throws SQLException;
    public void setURL(String url);
    public void setUser(String user);
    public void setPassword(String password);
}

JDBC Core Operations

JDBC Advanced Features

Advanced JDBC capabilities including connection pooling, distributed transactions (XA), batch operations, and server-side prepared statements.

// Connection pooling
public class MysqlConnectionPoolDataSource implements ConnectionPoolDataSource {
    public PooledConnection getPooledConnection() throws SQLException;
    public PooledConnection getPooledConnection(String user, String password) throws SQLException;
}

public class MysqlPooledConnection implements PooledConnection {
    public Connection getConnection() throws SQLException;
    public void close() throws SQLException;
    public void addConnectionEventListener(ConnectionEventListener listener);
}

// XA distributed transactions
public class MysqlXADataSource extends MysqlConnectionPoolDataSource implements XADataSource {
    public XAConnection getXAConnection() throws SQLException;
    public XAConnection getXAConnection(String user, String password) throws SQLException;
}

public class MysqlXAConnection extends MysqlPooledConnection implements XAConnection {
    public XAResource getXAResource() throws SQLException;
}

// Callable statements for stored procedures
public class CallableStatement extends PreparedStatement implements java.sql.CallableStatement {
    public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException;
    public void registerOutParameter(String parameterName, int sqlType) throws SQLException;
    public Object getObject(int parameterIndex) throws SQLException;
    public Object getObject(String parameterName) throws SQLException;
}

// Batch operations
public void addBatch(String sql) throws SQLException;
public int[] executeBatch() throws SQLException;
public void clearBatch() throws SQLException;

JDBC Advanced Features

JDBC High Availability

Load balancing, replication, and failover support for high-availability MySQL deployments.

// Load-balanced connection
public interface LoadBalancedConnection extends JdbcConnection {
    boolean addHost(String host) throws SQLException;
    void removeHost(String host) throws SQLException;
    void removeHostWhenNotInUse(String host) throws SQLException;
    void ping(boolean allConnections) throws SQLException;
}

// Replication connection
public interface ReplicationConnection extends JdbcConnection {
    long getConnectionGroupId();
    JdbcConnection getCurrentConnection();
    JdbcConnection getSourceConnection();
    void promoteReplicaToSource(String host) throws SQLException;
    void removeSourceHost(String host) throws SQLException;
    void removeSourceHost(String host, boolean waitUntilNotInUse) throws SQLException;
    boolean isHostSource(String host);
    JdbcConnection getReplicaConnection();
    void addReplicaHost(String host) throws SQLException;
    void removeReplica(String host) throws SQLException;
    void removeReplica(String host, boolean closeGently) throws SQLException;
    boolean isHostReplica(String host);
}

// Connection group management
public class ConnectionGroup {
    public void addHost(String host, boolean forExisting);
    public void removeHost(String host);
    public String getGroupName();
    public Collection<String> getInitialHosts();
    public int getInitialHostsSize();
}

public class ConnectionGroupManager {
    public static void registerConnectionGroup(String group, ConnectionGroup connectionGroup);
    public static ConnectionGroup getConnectionGroup(String group);
    public static void addHost(String group, String host, boolean forExisting);
    public static void removeHost(String group, String host) throws SQLException;
}

// Load balancing strategies
public interface BalanceStrategy {
    void init(Connection conn, Properties props) throws SQLException;
    Connection pickConnection(InvocationHandler proxy, List<String> hosts,
                            Map<String, JdbcConnection> connections,
                            long[] responseTimes, int numRetries) throws SQLException;
}

public interface LoadBalanceExceptionChecker {
    boolean shouldExceptionTriggerFailover(SQLException ex);
    void init(Connection conn, Properties props) throws SQLException;
    void destroy();
}

JDBC High Availability

X DevAPI Core

Core X DevAPI interfaces for session management, schema access, and basic document/table operations.

// Session factory
public class SessionFactory {
    public Session getSession(String url);
    public Session getSession(Properties properties);
}

// Client factory for connection pooling
public class ClientFactory {
    public Client getClient(String url, String clientPropsJson);
    public Client getClient(String url, Properties clientProps);
}

// Client interface
public interface Client extends Closeable {
    Session getSession();
    void close();
}

// Session interface
public interface Session extends Closeable {
    Schema getDefaultSchema();
    String getDefaultSchemaName();
    Schema getSchema(String schemaName);
    List<Schema> getSchemas();
    Schema createSchema(String schemaName);
    Schema createSchema(String schemaName, boolean reuseExisting);
    void dropSchema(String schemaName);
    String getUri();
    boolean isOpen();
    void close();
    SqlStatement sql(String sql);
    void startTransaction();
    void commit();
    void rollback();
    String setSavepoint();
    String setSavepoint(String name);
    void rollbackTo(String name);
    void releaseSavepoint(String name);
}

// Schema interface
public interface Schema extends DatabaseObject {
    Collection getCollection(String name);
    Collection getCollection(String name, boolean requireExists);
    Collection createCollection(String name);
    Collection createCollection(String name, boolean reuseExisting);
    Table getTable(String name);
    Table getTable(String name, boolean requireExists);
    List<Collection> getCollections();
    List<Collection> getCollections(String pattern);
    List<Table> getTables();
    List<Table> getTables(String pattern);
    void dropCollection(String collectionName);
}

// Collection interface
public interface Collection extends DatabaseObject {
    AddStatement add(Map<String, ?> doc);
    AddStatement add(String... jsonStrings);
    AddStatement add(DbDoc document);
    AddStatement add(DbDoc... docs);
    FindStatement find();
    FindStatement find(String searchCondition);
    ModifyStatement modify(String searchCondition);
    RemoveStatement remove(String searchCondition);
    DbDoc getOne(String id);
    Result replaceOne(String id, DbDoc doc);
    Result replaceOne(String id, String jsonString);
    Result addOrReplaceOne(String id, DbDoc doc);
    Result addOrReplaceOne(String id, String jsonString);
    Result removeOne(String id);
    long count();
    DbDoc newDoc();
    Result createIndex(String indexName, DbDoc indexDefinition);
    Result createIndex(String indexName, String indexDefinition);
    void dropIndex(String indexName);
}

// Table interface
public interface Table extends DatabaseObject {
    InsertStatement insert();
    InsertStatement insert(String... fields);
    SelectStatement select(String... projection);
    UpdateStatement update();
    DeleteStatement delete();
    long count();
    boolean isView();
}

X DevAPI Core

X DevAPI CRUD Operations

Fluent statement builders for Create, Read, Update, and Delete operations on collections and tables.

// Add documents to collection
public interface AddStatement extends Statement<AddStatement, AddResult> {
    AddStatement add(DbDoc... docs);
    AddStatement add(String... jsonStrings);
    AddResult execute();
}

// Find documents in collection
public interface FindStatement extends Statement<FindStatement, DocResult> {
    FindStatement fields(String... projection);
    FindStatement groupBy(String... fields);
    FindStatement having(String having);
    FindStatement orderBy(String... sortFields);
    FindStatement limit(long numberOfRows);
    FindStatement offset(long numberOfRows);
    FindStatement lockShared();
    FindStatement lockShared(Statement.LockContention lockContention);
    FindStatement lockExclusive();
    FindStatement lockExclusive(Statement.LockContention lockContention);
    FindStatement bind(String name, Object value);
    FindStatement bind(Map<String, Object> values);
    DocResult execute();
}

// Modify documents in collection
public interface ModifyStatement extends Statement<ModifyStatement, Result> {
    ModifyStatement set(String docPath, Object value);
    ModifyStatement change(String docPath, Object value);
    ModifyStatement unset(String... fields);
    ModifyStatement arrayInsert(String docPath, Object value);
    ModifyStatement arrayAppend(String docPath, Object value);
    ModifyStatement patch(DbDoc patch);
    ModifyStatement patch(String jsonPatch);
    ModifyStatement sort(String... sortFields);
    ModifyStatement limit(long numberOfRows);
    ModifyStatement bind(String name, Object value);
    ModifyStatement bind(Map<String, Object> values);
    Result execute();
}

// Remove documents from collection
public interface RemoveStatement extends Statement<RemoveStatement, Result> {
    RemoveStatement sort(String... sortFields);
    RemoveStatement limit(long numberOfRows);
    RemoveStatement bind(String name, Object value);
    RemoveStatement bind(Map<String, Object> values);
    Result execute();
}

// Insert rows into table
public interface InsertStatement extends Statement<InsertStatement, InsertResult> {
    InsertStatement values(Object... values);
    InsertResult execute();
}

// Select rows from table
public interface SelectStatement extends Statement<SelectStatement, RowResult> {
    SelectStatement where(String searchCondition);
    SelectStatement groupBy(String... fields);
    SelectStatement having(String having);
    SelectStatement orderBy(String... sortFields);
    SelectStatement limit(long numberOfRows);
    SelectStatement offset(long numberOfRows);
    SelectStatement lockShared();
    SelectStatement lockShared(Statement.LockContention lockContention);
    SelectStatement lockExclusive();
    SelectStatement lockExclusive(Statement.LockContention lockContention);
    SelectStatement bind(String name, Object value);
    SelectStatement bind(Map<String, Object> values);
    RowResult execute();
}

// Update rows in table
public interface UpdateStatement extends Statement<UpdateStatement, Result> {
    UpdateStatement set(String field, Object value);
    UpdateStatement where(String searchCondition);
    UpdateStatement orderBy(String... sortFields);
    UpdateStatement limit(long numberOfRows);
    UpdateStatement bind(String name, Object value);
    UpdateStatement bind(Map<String, Object> values);
    Result execute();
}

// Delete rows from table
public interface DeleteStatement extends Statement<DeleteStatement, Result> {
    DeleteStatement where(String searchCondition);
    DeleteStatement orderBy(String... sortFields);
    DeleteStatement limit(long numberOfRows);
    DeleteStatement bind(String name, Object value);
    DeleteStatement bind(Map<String, Object> values);
    Result execute();
}

X DevAPI CRUD Operations

X DevAPI SQL Operations

Direct SQL execution and result handling within the X DevAPI context.

// SQL statement execution
public interface SqlStatement extends Statement<SqlStatement, SqlResult> {
    SqlStatement bind(Object... values);
    SqlStatement bind(List<Object> values);
    SqlStatement bind(Map<String, Object> values);
    SqlResult execute();
}

// SQL result handling
public interface SqlResult extends Result, RowResult, Iterator<Row> {
    boolean hasData();
    SqlResult nextResult();
    long getAutoIncrementValue();
    long getAffectedItemsCount();
    int getWarningsCount();
    Iterator<Warning> getWarnings();
}

// Result types
public interface Result {
    long getAffectedItemsCount();
    int getWarningsCount();
    Iterator<Warning> getWarnings();
}

public interface DocResult extends FetchResult<DbDoc>, Iterator<DbDoc> {
    int count();
    List<DbDoc> fetchAll();
}

public interface RowResult extends FetchResult<Row>, Iterator<Row> {
    int getColumnCount();
    List<Column> getColumns();
    List<String> getColumnNames();
    int count();
    List<Row> fetchAll();
}

public interface AddResult extends Result {
    List<String> getGeneratedIds();
}

public interface InsertResult extends Result {
    Long getAutoIncrementValue();
}

X DevAPI SQL Operations

Configuration and Connection URLs

Connection URL parsing, property management, and host information for configuring database connections.

// Connection URL
public class ConnectionUrl {
    public static ConnectionUrl getConnectionUrlInstance(String connString, Properties info);
    public Type getType();
    public String getDatabase();
    public int getDefaultPort();
    public String getDefaultHost();
    public List<HostInfo> getHostsList();
    public HostInfo getMainHost();
    public Properties getOriginalProperties();
    public Properties getConnectionArgumentsAsProperties();
}

// Host information
public class HostInfo {
    public String getHost();
    public int getPort();
    public String getUser();
    public String getPassword();
    public String getDatabase();
    public Map<String, String> getHostProperties();
    public String getProperty(String key);
}

// Property keys (partial listing - over 200 properties available)
// See configuration.md for complete documentation
public enum PropertyKey {
    // Connection properties
    USER("user"),
    PASSWORD("password"),
    DBNAME("dbname"),
    HOST("host"),
    PORT("port"),

    // Configuration properties
    useSSL("useSSL"),
    requireSSL("requireSSL"),
    verifyServerCertificate("verifyServerCertificate"),
    trustCertificateKeyStoreUrl("trustCertificateKeyStoreUrl"),
    trustCertificateKeyStorePassword("trustCertificateKeyStorePassword"),
    clientCertificateKeyStoreUrl("clientCertificateKeyStoreUrl"),
    clientCertificateKeyStorePassword("clientCertificateKeyStorePassword"),

    // Performance properties
    cachePrepStmts("cachePrepStmts"),
    prepStmtCacheSize("prepStmtCacheSize"),
    prepStmtCacheSqlLimit("prepStmtCacheSqlLimit"),
    useServerPrepStmts("useServerPrepStmts"),
    useLocalSessionState("useLocalSessionState"),
    rewriteBatchedStatements("rewriteBatchedStatements"),

    // Timeout properties
    connectTimeout("connectTimeout"),
    socketTimeout("socketTimeout"),
    connectionLifecycleInterceptors("connectionLifecycleInterceptors"),

    // Character encoding and timezone
    characterEncoding("characterEncoding"),
    connectionCollation("connectionCollation"),
    connectionTimeZone("connectionTimeZone", "serverTimezone"),  // serverTimezone is an alias

    // Logging
    logger("logger"),
    profileSQL("profileSQL"),
    useUsageAdvisor("useUsageAdvisor");

    private final String keyName;
    private final String alias;
    PropertyKey(String keyName) {
        this(keyName, null);
    }
    PropertyKey(String keyName, String alias) {
        this.keyName = keyName;
        this.alias = alias;
    }
    public String getKeyName() { return keyName; }
}

// Property set interface
public interface PropertySet {
    void initializeProperties(Properties props);
    <T> RuntimeProperty<T> getProperty(PropertyKey key);
    <T> RuntimeProperty<T> getProperty(String name);
    RuntimeProperty<Boolean> getBooleanProperty(PropertyKey key);
    RuntimeProperty<Integer> getIntegerProperty(PropertyKey key);
    RuntimeProperty<Long> getLongProperty(PropertyKey key);
    RuntimeProperty<String> getStringProperty(PropertyKey key);
}

// Property definitions
public interface PropertyDefinition<T> {
    String getName();
    T getDefaultValue();
    boolean hasValueConstraints();
    boolean isRangeBased();
    String[] getAllowableValues();
    int getLowerBound();
    int getUpperBound();
}

// Runtime property
public interface RuntimeProperty<T> {
    PropertyDefinition<T> getPropertyDefinition();
    void initializeFrom(Properties extractFrom);
    T getValue();
    void setValue(T value);
    boolean isExplicitlySet();
}

// Connection properties transform
public interface ConnectionPropertiesTransform {
    Properties transformProperties(Properties props);
}

Configuration and Connection URLs

Exception Handling

Comprehensive exception hierarchy for handling errors and exceptional conditions throughout the driver.

// Base exception
public class CJException extends RuntimeException {
    public CJException();
    public CJException(String message);
    public CJException(Throwable cause);
    public CJException(String message, Throwable cause);
}

// Communication exceptions
public class CJCommunicationsException extends CJException {
    public CJCommunicationsException(String message);
    public CJCommunicationsException(String message, Throwable cause);
}

public class CommunicationsException extends SQLException {
    public CommunicationsException(String message, Throwable underlyingException);
}

// Timeout and cancellation
public class CJTimeoutException extends CJException {
    public CJTimeoutException(String message);
}

public class MySQLTimeoutException extends SQLException {
    public MySQLTimeoutException();
    public MySQLTimeoutException(String message);
}

public class MySQLStatementCancelledException extends SQLException {
    public MySQLStatementCancelledException();
    public MySQLStatementCancelledException(String message);
}

public class MySQLQueryInterruptedException extends SQLException {
    public MySQLQueryInterruptedException();
}

// Transaction exceptions
public class MySQLTransactionRollbackException extends SQLException
    implements DeadlockTimeoutRollbackMarker {
    public MySQLTransactionRollbackException();
    public MySQLTransactionRollbackException(String message);
}

// Data exceptions
public class DataConversionException extends CJException {
    public DataConversionException(String message);
}

public class DataReadException extends CJException {
    public DataReadException(String message);
    public DataReadException(Throwable cause);
}

public class DataTruncationException extends CJException {
    public DataTruncationException(String message);
}

public class MysqlDataTruncation extends DataTruncation {
    public MysqlDataTruncation(String message, int index, boolean parameter,
                              boolean read, int dataSize, int transferSize, int vendorErrorCode);
}

// Connection exceptions
public class ConnectionIsClosedException extends CJException {
    public ConnectionIsClosedException();
    public ConnectionIsClosedException(String message);
}

public class UnableToConnectException extends CJException {
    public UnableToConnectException(String message);
    public UnableToConnectException(String message, Throwable cause);
}

public class CJConnectionFeatureNotAvailableException extends CJException {
    public CJConnectionFeatureNotAvailableException();
}

public class ConnectionFeatureNotAvailableException extends SQLException {
    public ConnectionFeatureNotAvailableException(String message, Throwable underlyingException);
}

// Operation exceptions
public class CJOperationNotSupportedException extends CJException {
    public CJOperationNotSupportedException();
    public CJOperationNotSupportedException(String message);
}

public class OperationNotSupportedException extends SQLException {
    public OperationNotSupportedException();
    public OperationNotSupportedException(String message);
}

public class OperationCancelledException extends CJException {
    public OperationCancelledException(String message);
}

// Authentication and security
public class PasswordExpiredException extends CJException {
    public PasswordExpiredException();
    public PasswordExpiredException(String message);
}

public class ClosedOnExpiredPasswordException extends SQLException {
    public ClosedOnExpiredPasswordException();
}

public class RSAException extends CJException {
    public RSAException(String message);
    public RSAException(String message, Throwable cause);
}

public class SSLParamsException extends CJException {
    public SSLParamsException(String message);
    public SSLParamsException(String message, Throwable cause);
}

// Packet and protocol exceptions
public class CJPacketTooBigException extends CJException {
    public CJPacketTooBigException();
    public CJPacketTooBigException(String message);
}

public class PacketTooBigException extends SQLException {
    public PacketTooBigException(long packetSize);
}

// Other exceptions
public class WrongArgumentException extends CJException {
    public WrongArgumentException(String message);
}

public class InvalidConnectionAttributeException extends CJException {
    public InvalidConnectionAttributeException(String message);
}

public class PropertyNotModifiableException extends CJException {
    public PropertyNotModifiableException(String message);
}

public class UnsupportedConnectionStringException extends CJException {
    public UnsupportedConnectionStringException();
}

public class NumberOutOfRange extends CJException {
    public NumberOutOfRange(String message);
}

public class FeatureNotAvailableException extends CJException {
    public FeatureNotAvailableException(String message);
}

public class AssertionFailedException extends CJException {
    public AssertionFailedException(String message);
}

public class NotUpdatable extends SQLException {
    public NotUpdatable(String message);
}

// Exception interceptor
public interface ExceptionInterceptor {
    ExceptionInterceptor init(Properties props, Log log);
    void destroy();
    Exception interceptException(Exception sqlEx);
}

// Exception factory
public class ExceptionFactory {
    public static <T extends CJException> T createException(Class<T> clazz, String message);
    public static <T extends CJException> T createException(Class<T> clazz, Throwable cause);
    public static <T extends CJException> T createException(Class<T> clazz, String message, Throwable cause);
}

// MySQL error numbers
public class MysqlErrorNumbers {
    // Server error codes
    public static final int ER_HASHCHK = 1000;
    public static final int ER_NISAMCHK = 1001;
    public static final int ER_NO = 1002;
    public static final int ER_YES = 1003;
    // ... (many more error codes)
    public static final int ER_MUST_CHANGE_PASSWORD = 1820;
    public static final int ER_MUST_CHANGE_PASSWORD_LOGIN = 1862;
}

// SQL error mapping
public class SQLError {
    public static SQLException createSQLException(String message, String sqlState,
                                                 ExceptionInterceptor interceptor);
    public static String get(String key);
}

// X DevAPI error
public class XDevAPIError extends CJException {
    public XDevAPIError(String message);
    public XDevAPIError(String message, Throwable cause);
}

Exception Handling

Authentication and Security

Authentication callbacks and security mechanisms for various authentication methods.

// Callback interfaces
public interface MysqlCallback {
    // Marker interface for callbacks
}

public interface MysqlCallbackHandler {
    void handle(MysqlCallback callback);
}

// OpenID Connect authentication
public class OpenidConnectAuthenticationCallback implements MysqlCallback {
    public OpenidConnectAuthenticationCallback();
    public void setIdToken(String idToken);
    public String getIdToken();
}

public class OpenidConnectIdTokenFromFileCallbackHandler implements MysqlCallbackHandler {
    public OpenidConnectIdTokenFromFileCallbackHandler(String idTokenFile);
    public void handle(MysqlCallback callback);
}

// WebAuthn authentication
public class WebAuthnAuthenticationCallback implements MysqlCallback {
    public WebAuthnAuthenticationCallback();
    public void setAuthenticatorData(byte[] authenticatorData);
    public byte[] getAuthenticatorData();
    public void setSignature(byte[] signature);
    public byte[] getSignature();
    public void setRelyingPartyId(String relyingPartyId);
    public String getRelyingPartyId();
    public void setChallenge(byte[] challenge);
    public byte[] getChallenge();
}

// Username callback
public class UsernameCallback implements MysqlCallback {
    public UsernameCallback();
    public void setUsername(String username);
    public String getUsername();
}

// Authentication plugin interface
public interface AuthenticationPlugin<M extends Message> {
    void init(Protocol<M> prot, MysqlCallbackHandler cbh);
    void reset();
    void destroy();
    String getProtocolPluginName();
    boolean requiresConfidentiality();
    boolean isReusable();
    void setAuthenticationParameters(String user, String password);
    boolean nextAuthenticationStep(M fromServer, List<M> toServer);
}

// Authentication provider
public interface AuthenticationProvider<M extends Message> {
    void init(Protocol<M> prot, PropertySet propertySet, ExceptionInterceptor exceptionInterceptor);
    void connect(String userName, String password, String database);
    void changeUser(String userName, String password, String database);
}

Authentication and Security

Logging and Monitoring

Logging interfaces and implementations, plus profiling capabilities for monitoring driver behavior.

// Log interface
public interface Log {
    boolean isDebugEnabled();
    boolean isErrorEnabled();
    boolean isFatalEnabled();
    boolean isInfoEnabled();
    boolean isTraceEnabled();
    boolean isWarnEnabled();

    void logDebug(Object msg);
    void logDebug(Object msg, Throwable thrown);
    void logError(Object msg);
    void logError(Object msg, Throwable thrown);
    void logFatal(Object msg);
    void logFatal(Object msg, Throwable thrown);
    void logInfo(Object msg);
    void logInfo(Object msg, Throwable thrown);
    void logTrace(Object msg);
    void logTrace(Object msg, Throwable thrown);
    void logWarn(Object msg);
    void logWarn(Object msg, Throwable thrown);
}

// Standard logger implementation
public class StandardLogger implements Log {
    public StandardLogger(String name);
    public StandardLogger(String name, boolean logLocationInfo);
    // ... implements all Log methods
}

// SLF4J logger implementation
public class Slf4JLogger implements Log {
    public Slf4JLogger(String name);
    // ... implements all Log methods
}

// JDK 1.4 logger implementation
public class Jdk14Logger implements Log {
    public Jdk14Logger(String name);
    // ... implements all Log methods
}

// Null logger (no-op)
public class NullLogger implements Log {
    public NullLogger(String instanceName);
    // ... implements all Log methods as no-ops
}

// Profiler event interface
public interface ProfilerEvent {
    byte getEventType();
    String getCatalog();
    long getConnectionId();
    int getResultSetColumnCount();
    long getResultSetRowsCount();
    String getMessage();
    long getEventCreationTime();
    long getEventDuration();
    String getDurationUnits();
    String getEventCreationPointAsString();
}

// Profiler event handler
public interface ProfilerEventHandler {
    void init(Log log);
    void destroy();
    void consumeEvent(ProfilerEvent evt);
}

// Log utility
public class LogUtils {
    public static void logInfo(Log logger, Object message);
    public static void logDebug(Log logger, Object message);
    public static void logWarn(Log logger, Object message);
    public static void logError(Log logger, Object message);
    public static void logFatal(Log logger, Object message);
    public static void logTrace(Log logger, Object message);
}

Logging and Monitoring

Interceptors

Query and connection lifecycle interceptors for customizing driver behavior.

// Query interceptor interface
public interface QueryInterceptor {
    QueryInterceptor init(MysqlConnection conn, Properties props, Log log);

    <T extends Resultset> T preProcess(Supplier<String> sql, Query interceptedQuery);

    boolean executeTopLevelOnly();

    void destroy();

    <T extends Resultset> T postProcess(Supplier<String> sql, Query interceptedQuery,
                                       T originalResultSet, ServerSession serverSession);
}

// Connection lifecycle interceptor interface
public interface ConnectionLifecycleInterceptor {
    ConnectionLifecycleInterceptor init(MysqlConnection conn, Properties props, Log log);

    void destroy();

    void createNewSession();

    void transactionBegun();

    void transactionCompleted();
}

// Pre-built interceptors
public class ResultSetScannerInterceptor implements QueryInterceptor {
    public QueryInterceptor init(MysqlConnection conn, Properties props, Log log);
    // Scans result sets for specific patterns
}

public class ServerStatusDiffInterceptor implements QueryInterceptor {
    public QueryInterceptor init(MysqlConnection conn, Properties props, Log log);
    // Tracks server status changes
}

public class SessionAssociationInterceptor implements ConnectionLifecycleInterceptor {
    public ConnectionLifecycleInterceptor init(MysqlConnection conn, Properties props, Log log);
    // Associates sessions with application context
}

public class LoadBalancedAutoCommitInterceptor implements QueryInterceptor {
    public QueryInterceptor init(MysqlConnection conn, Properties props, Log log);
    // Handles auto-commit in load-balanced environments
}

Interceptors

Utilities

Utility classes for string manipulation, time handling, encoding, and other common operations.

// String utilities
public class StringUtils {
    public static String toString(byte[] bytes);
    public static String toString(byte[] bytes, int offset, int length);
    public static String toString(byte[] bytes, String encoding);
    public static String toString(byte[] bytes, int offset, int length, String encoding);
    public static byte[] getBytes(String s);
    public static byte[] getBytes(String s, String encoding);

    public static boolean isNullOrEmpty(String str);
    public static String stripComments(String src, String stringOpens, String stringCloses,
                                      boolean slashStarComments, boolean slashSlashComments,
                                      boolean hashComments, boolean dashDashComments);

    public static int indexOfIgnoreCase(String searchIn, String searchFor);
    public static int indexOfIgnoreCase(int startingPosition, String searchIn, String searchFor);

    public static List<String> split(String stringVal, String delimiter, boolean trim);
    public static String[] split(String stringVal, String delimiter, String markers,
                                String markerCloses, boolean trim);
}

// String inspector for query parsing
public class StringInspector {
    public StringInspector(String source);
    public int indexOfIgnoreCase(int startPos, String searchFor);
    public int indexOfIgnoreCase(int startPos, String searchFor,
                                String openingMarkers, String closingMarkers,
                                SearchMode searchMode);
    public String substring(int beginIndex, int endIndex);
}

// Search mode enum
public enum SearchMode {
    ALLOW_BACKSLASH_ESCAPE,
    SKIP_BETWEEN_MARKERS,
    SKIP_BLOCK_COMMENTS,
    SKIP_LINE_COMMENTS,
    SKIP_WHITE_SPACE;
}

// Time utilities
public class TimeUtil {
    public static Time adjustTime(Time time, Calendar fromCal, Calendar toCal);
    public static Timestamp adjustTimestamp(Timestamp timestamp, Calendar fromCal, Calendar toCal);
    public static Timestamp adjustTimestamp(Timestamp timestamp, TimeZone fromTz, TimeZone toTz);

    public static Time parseTime(String timeStr, Calendar cal);
    public static Timestamp parseTimestamp(String timestampStr, Calendar cal);
    public static Date parseDate(String dateStr, Calendar cal);
}

// Base64 decoder
public class Base64Decoder {
    public Base64Decoder();
    public byte[] decode(byte[] base64Data);
    public byte[] decode(String base64String);
}

// DNS SRV record handling
public class DnsSrv {
    public static class SrvRecord {
        public String getHost();
        public int getPort();
        public int getPriority();
        public int getWeight();
    }

    public static List<SrvRecord> lookupSrvRecords(String serviceName);
    public static List<SrvRecord> sortSrvRecords(List<SrvRecord> records);
}

// LRU cache
public class LRUCache<K, V> {
    public LRUCache(int maxElements);
    public void put(K key, V value);
    public V get(K key);
    public void clear();
    public int size();
}

// Data type utilities
public class DataTypeUtil {
    public static int getJdbcType(String mysqlType);
    public static String getJavaEncodingFromMysqlCharset(String mysqlCharset);
    public static String getMysqlCharsetFromJavaEncoding(String javaEncoding);
}

// Escape tokenizer for JDBC escape sequences
public class EscapeTokenizer {
    public EscapeTokenizer(String s);
    public boolean hasMoreTokens();
    public String nextToken();
    public char getLastChar();
}

// Lazy string evaluation
public class LazyString {
    public LazyString(byte[] buffer, int offset, int length, String encoding);
    public String toString();
    public int length();
}

// SASLprep for authentication
public class SaslPrep {
    public static String prepare(String str);
    public static String prepare(String str, boolean allowUnassigned);
}

// Sequential ID lease for connection pools
public class SequentialIdLease {
    public SequentialIdLease();
    public int allocate();
    public void release(int id);
}

// Utilities class
public class Util {
    public static boolean isJdbc4();
    public static boolean isJdbc42();
    public static String stackTraceToString(Throwable t);
    public static boolean isCommunityEdition(String serverVersion);
    public static boolean isEnterpriseEdition(String serverVersion);
}

// Test utilities
public class TestUtils {
    public static Properties getPropertiesFromTestsuiteUrl();
    public static String getBuildTestUrl(Properties props);
    public static Connection getConnection() throws SQLException;
}

Utilities

Type System

MySQL type enumeration, charset mapping, server version handling, and type conversion utilities for mapping between MySQL, JDBC, and Java types.

// MySQL type enumeration
public enum MysqlType implements SQLType {
    // Numeric types
    BIT, TINYINT, TINYINT_UNSIGNED, SMALLINT, SMALLINT_UNSIGNED,
    MEDIUMINT, MEDIUMINT_UNSIGNED, INT, INT_UNSIGNED, BIGINT, BIGINT_UNSIGNED,
    FLOAT, FLOAT_UNSIGNED, DOUBLE, DOUBLE_UNSIGNED, DECIMAL, DECIMAL_UNSIGNED,
    BOOLEAN,

    // Date and time types
    DATE, TIME, DATETIME, TIMESTAMP, YEAR,

    // String types
    CHAR, VARCHAR, TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT,

    // Binary types
    BINARY, VARBINARY, TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOB,

    // Special types
    JSON, ENUM, SET, GEOMETRY, VECTOR, NULL, UNKNOWN;

    public String getName();
    public int getJdbcType();
    public String getClassName();
    public static MysqlType getByName(String mysqlTypeName);
    public static MysqlType getByJdbcType(int jdbcType);
}

// Charset mapping
public class CharsetMapping {
    public static String getJavaEncodingForMysqlCharset(String mysqlCharsetName);
    public static String getMysqlCharsetForJavaEncoding(String javaEncoding, ServerVersion version);
    public static boolean isMultibyteCharset(String javaEncodingName);
}

// Server version
public class ServerVersion implements Comparable<ServerVersion> {
    public ServerVersion(int major, int minor, int subminor);
    public ServerVersion(String versionString);
    public boolean meetsMinimum(ServerVersion version);
    public int compareTo(ServerVersion other);
}

Type System

Common Types

DbDoc and JSON Types

// Document interface
public interface DbDoc extends JsonValue, Map<String, JsonValue> {
    DbDoc add(String key, JsonValue value);
    JsonValue get(Object key); // Inherited from Map
    JsonValue remove(Object key); // Inherited from Map
    int size(); // Inherited from Map
    Set<String> keySet(); // Inherited from Map
}

// JSON value types
public interface JsonValue {
    // Base interface for all JSON values
    default String toFormattedString();
}

public class JsonString implements JsonValue {
    public JsonString();
    public JsonString setValue(String value);
    public String getString();
}

public class JsonNumber implements JsonValue {
    public JsonNumber();
    public JsonNumber setValue(String value);
    public String getString();
    public Integer getInteger();
    public BigDecimal getBigDecimal();
}

public class JsonArray extends ArrayList<JsonValue> implements JsonValue {
    public JsonArray();
    public JsonArray addValue(JsonValue val); // Convenience method
    // Inherited from ArrayList: add(), get(), size(), remove(), clear(), etc.
}

public enum JsonLiteral implements JsonValue {
    TRUE,
    FALSE,
    NULL;
}

// DbDoc implementation
public class DbDocImpl implements DbDoc {
    public DbDocImpl();
    public DbDocImpl(String jsonString);
    // ... implements all DbDoc methods
}

Expression and Query Types

// Expression wrapper
public class Expression {
    public static Expression expr(String expressionString);
    public String getExpressionString();
}

// Column types
public enum Type {
    BIT, TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT,
    FLOAT, DECIMAL, DOUBLE,
    JSON, STRING, BYTES,
    TIME, DATE, DATETIME, TIMESTAMP,
    SET, ENUM, GEOMETRY;
}

// Column interface
public interface Column {
    String getSchemaName();
    String getTableName();
    String getTableLabel();
    String getColumnName();
    String getColumnLabel();
    Type getType();
    long getLength();
    int getFractionalDigits();
    boolean isNumberSigned();
    String getCollationName();
    String getCharacterSetName();
    boolean isPadded();
    boolean isNullable();
    boolean isAutoIncrement();
    boolean isPrimaryKey();
    boolean isUniqueKey();
    boolean isPartKey();
}

// Row interface
public interface Row {
    Object getObject(int pos);
    Object getObject(String columnName);
    DbDoc toDbDoc();
    String getString(int pos);
    String getString(String columnName);
    int getInt(int pos);
    int getInt(String columnName);
    long getLong(int pos);
    long getLong(String columnName);
    boolean getBoolean(int pos);
    boolean getBoolean(String columnName);
    byte[] getBytes(int pos);
    byte[] getBytes(String columnName);
    Date getDate(int pos);
    Date getDate(String columnName);
    Timestamp getTimestamp(int pos);
    Timestamp getTimestamp(String columnName);
    Time getTime(int pos);
    Time getTime(String columnName);
    BigDecimal getBigDecimal(int pos);
    BigDecimal getBigDecimal(String columnName);
}

Warning Interface

public interface Warning {
    int getLevel();
    long getCode();
    String getMessage();
}