JDBC Type 4 driver for MySQL with X DevAPI support for document store operations
Connection URL parsing, property management, and host information for configuring database connections. These classes handle connection string parsing and property validation.
Parse and manage MySQL connection URLs.
package com.mysql.cj.conf;
public class ConnectionUrl {
// Create ConnectionUrl from connection string
public static ConnectionUrl getConnectionUrlInstance(String connString, Properties info);
// Get connection type
public Type getType();
// Database information
public String getDatabase();
// Default connection settings
public int getDefaultPort();
public String getDefaultHost();
// Host information
public List<HostInfo> getHostsList();
public HostInfo getMainHost();
// Properties
public Properties getOriginalProperties();
public Properties getConnectionArgumentsAsProperties();
// URL types
public enum Type {
SINGLE_CONNECTION("jdbc:mysql:", HostsCardinality.SINGLE),
FAILOVER_CONNECTION("jdbc:mysql:", HostsCardinality.MULTIPLE),
LOADBALANCE_CONNECTION("jdbc:mysql:loadbalance:", HostsCardinality.ONE_OR_MORE),
REPLICATION_CONNECTION("jdbc:mysql:replication:", HostsCardinality.ONE_OR_MORE),
XDEVAPI_SESSION("mysqlx:", HostsCardinality.ONE_OR_MORE);
private final String protocol;
private final HostsCardinality cardinality;
Type(String protocol, HostsCardinality cardinality) {
this.protocol = protocol;
this.cardinality = cardinality;
}
public String getProtocol() { return protocol; }
public HostsCardinality getCardinality() { return cardinality; }
}
public enum HostsCardinality {
SINGLE,
MULTIPLE,
ONE_OR_MORE;
}
}
public class ConnectionUrlParser {
// Parse connection URL string
public static ConnectionUrl parseConnectionString(String connString);
// Validate URL format
public static boolean isConnectionStringSupported(String connString);
}Usage:
// Parse JDBC URL
String url = "jdbc:mysql://localhost:3306/mydb?useSSL=true&serverTimezone=UTC";
ConnectionUrl connUrl = ConnectionUrl.getConnectionUrlInstance(url, new Properties());
System.out.println("Type: " + connUrl.getType());
System.out.println("Database: " + connUrl.getDatabase());
System.out.println("Default port: " + connUrl.getDefaultPort());
// Get host information
List<HostInfo> hosts = connUrl.getHostsList();
for (HostInfo host : hosts) {
System.out.println("Host: " + host.getHost() + ":" + host.getPort());
}
// Parse load-balanced URL
String lbUrl = "jdbc:mysql:loadbalance://server1:3306,server2:3306/mydb";
ConnectionUrl lbConnUrl = ConnectionUrl.getConnectionUrlInstance(lbUrl, new Properties());
// Parse replication URL
String replUrl = "jdbc:mysql:replication://source:3306,replica1:3306,replica2:3306/mydb";
ConnectionUrl replConnUrl = ConnectionUrl.getConnectionUrlInstance(replUrl, new Properties());
// Parse X DevAPI URL
String xUrl = "mysqlx://root:password@localhost:33060/mydb";
ConnectionUrl xConnUrl = ConnectionUrl.getConnectionUrlInstance(xUrl, new Properties());Detailed information about database hosts.
package com.mysql.cj.conf;
public class HostInfo {
// Constructor
public HostInfo(ConnectionUrl connUrl, String host, int port, String user, String password);
public HostInfo(ConnectionUrl connUrl, String host, int port, String user, String password,
Map<String, String> properties);
// Host connection details
public String getHost();
public int getPort();
public String getHostPortPair();
// Authentication
public String getUser();
public String getPassword();
// Database
public String getDatabase();
// Properties
public Map<String, String> getHostProperties();
public String getProperty(String key);
// Expand host info (for DNS SRV records)
public boolean isPasswordless();
// String representation
public String toString();
}Usage:
ConnectionUrl connUrl = ConnectionUrl.getConnectionUrlInstance(
"jdbc:mysql://user:pass@localhost:3306/mydb",
new Properties()
);
HostInfo hostInfo = connUrl.getMainHost();
System.out.println("Host: " + hostInfo.getHost());
System.out.println("Port: " + hostInfo.getPort());
System.out.println("User: " + hostInfo.getUser());
System.out.println("Database: " + hostInfo.getDatabase());
// Get host properties
Map<String, String> props = hostInfo.getHostProperties();
for (Map.Entry<String, String> entry : props.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}Enumeration of all connection properties.
package com.mysql.cj.conf;
public enum PropertyKey {
// Connection basics
USER("user"),
PASSWORD("password"),
DBNAME("dbname"),
HOST("host"),
PORT("port"),
PROTOCOL("protocol"),
// SSL/TLS
useSSL("useSSL"),
requireSSL("requireSSL"),
verifyServerCertificate("verifyServerCertificate"),
trustCertificateKeyStoreUrl("trustCertificateKeyStoreUrl"),
trustCertificateKeyStorePassword("trustCertificateKeyStorePassword"),
trustCertificateKeyStoreType("trustCertificateKeyStoreType"),
clientCertificateKeyStoreUrl("clientCertificateKeyStoreUrl"),
clientCertificateKeyStorePassword("clientCertificateKeyStorePassword"),
clientCertificateKeyStoreType("clientCertificateKeyStoreType"),
sslMode("sslMode"),
enabledSSLCipherSuites("enabledSSLCipherSuites"),
enabledTLSProtocols("enabledTLSProtocols"),
// Performance
cachePrepStmts("cachePrepStmts"),
prepStmtCacheSize("prepStmtCacheSize"),
prepStmtCacheSqlLimit("prepStmtCacheSqlLimit"),
useServerPrepStmts("useServerPrepStmts"),
useLocalSessionState("useLocalSessionState"),
rewriteBatchedStatements("rewriteBatchedStatements"),
cacheResultSetMetadata("cacheResultSetMetadata"),
cacheServerConfiguration("cacheServerConfiguration"),
elideSetAutoCommits("elideSetAutoCommits"),
maintainTimeStats("maintainTimeStats"),
// Timeouts
connectTimeout("connectTimeout"),
socketTimeout("socketTimeout"),
// Character encoding
characterEncoding("characterEncoding"),
connectionCollation("connectionCollation"),
useUnicode("useUnicode"),
// Logging
logger("logger"),
profileSQL("profileSQL"),
useUsageAdvisor("useUsageAdvisor"),
logSlowQueries("logSlowQueries"),
slowQueryThresholdMillis("slowQueryThresholdMillis"),
// Load balancing
loadBalanceStrategy("loadBalanceStrategy"),
loadBalanceExceptionChecker("loadBalanceExceptionChecker"),
loadBalanceAutoCommitStatementThreshold("loadBalanceAutoCommitStatementThreshold"),
loadBalanceConnectionGroup("loadBalanceConnectionGroup"),
// Replication
replicationConnectionGroup("replicationConnectionGroup"),
// High availability
autoReconnect("autoReconnect"),
autoReconnectForPools("autoReconnectForPools"),
failOverReadOnly("failOverReadOnly"),
maxReconnects("maxReconnects"),
retriesAllDown("retriesAllDown"),
// Transaction
autoCommit("autoCommit"),
defaultTransactionIsolation("defaultTransactionIsolation"),
// Result sets
defaultFetchSize("defaultFetchSize"),
maxRows("maxRows"),
useCursorFetch("useCursorFetch"),
// Server configuration
connectionTimeZone("connectionTimeZone", "serverTimezone"), // serverTimezone is an alias
forceConnectionTimeZoneToSession("forceConnectionTimeZoneToSession"),
// Metadata
useInformationSchema("useInformationSchema"),
getProceduresReturnsFunctions("getProceduresReturnsFunctions"),
// Interceptors
queryInterceptors("queryInterceptors"),
connectionLifecycleInterceptors("connectionLifecycleInterceptors"),
exceptionInterceptors("exceptionInterceptors"),
// Authentication
authenticationPlugins("authenticationPlugins"),
defaultAuthenticationPlugin("defaultAuthenticationPlugin"),
disabledAuthenticationPlugins("disabledAuthenticationPlugins"),
// Other
allowLoadLocalInfile("allowLoadLocalInfile"),
allowMultiQueries("allowMultiQueries"),
allowPublicKeyRetrieval("allowPublicKeyRetrieval"),
connectionAttributes("connectionAttributes"),
propertiesTransform("propertiesTransform"),
zeroDateTimeBehavior("zeroDateTimeBehavior");
private final String keyName;
PropertyKey(String keyName) {
this.keyName = keyName;
}
public String getKeyName() {
return keyName;
}
public static PropertyKey fromKeyName(String keyName);
}Interface for managing connection properties.
package com.mysql.cj.conf;
import java.util.Properties;
public interface PropertySet {
void addProperty(RuntimeProperty<?> prop);
void removeProperty(String name);
void removeProperty(PropertyKey key);
<T> RuntimeProperty<T> getProperty(String name);
<T> RuntimeProperty<T> getProperty(PropertyKey key);
RuntimeProperty<Boolean> getBooleanProperty(String name);
RuntimeProperty<Boolean> getBooleanProperty(PropertyKey key);
RuntimeProperty<Integer> getIntegerProperty(String name);
RuntimeProperty<Integer> getIntegerProperty(PropertyKey key);
RuntimeProperty<Long> getLongProperty(String name);
RuntimeProperty<Long> getLongProperty(PropertyKey key);
RuntimeProperty<Integer> getMemorySizeProperty(String name);
RuntimeProperty<Integer> getMemorySizeProperty(PropertyKey key);
RuntimeProperty<String> getStringProperty(String name);
RuntimeProperty<String> getStringProperty(PropertyKey key);
<T extends Enum<T>> RuntimeProperty<T> getEnumProperty(String name);
<T extends Enum<T>> RuntimeProperty<T> getEnumProperty(PropertyKey key);
/**
* Initializes the property set with driver properties that come from URL or passed to
* the driver manager.
*
* @param props properties
*/
void initializeProperties(Properties props);
void postInitialization();
Properties exposeAsProperties();
/**
* Reset all properties to their initial values.
*/
void reset();
}Interface for property metadata.
package com.mysql.cj.conf;
import com.mysql.cj.exceptions.ExceptionInterceptor;
public interface PropertyDefinition<T> {
/**
* Does the property have fixed values based constraints.
*
* @return true if property has fixed values based constraints
*/
boolean hasValueConstraints();
/**
* Returns true if property has range-based constraints
*
* @return true if property has range-based constraints
*/
boolean isRangeBased();
/**
* Get the property key.
*
* @return PropertyKey or null if it's a custom property
*/
PropertyKey getPropertyKey();
/**
* Returns the property name.
*
* @return the property name
*/
String getName();
/**
* Returns the property camel-case alias.
*
* @return the property camel-case alias
*/
String getCcAlias();
/**
* Returns true if property has a camel-case alias.
*
* @return true if property has a camel-case alias
*/
boolean hasCcAlias();
/**
* Returns the default value.
*
* @return default value
*/
T getDefaultValue();
/**
* May the property be changed after initialization.
*
* @return true if the property value may be changed after initialization
*/
boolean isRuntimeModifiable();
/**
* Returns the property description. Used for documentation.
*
* @return property description
*/
String getDescription();
/**
* Returns the driver version where the property was introduced first. Used for documentation.
*
* @return the driver version where the property was introduced first
*/
String getSinceVersion();
/**
* Returns the property category.
*
* @return property category
*/
String getCategory();
/**
* Returns the property order. Used as preferred property position in properties table in documentation.
*
* @return property order
*/
int getOrder();
/**
* Returns the list of allowable values.
*
* @return the list of allowable values
*/
String[] getAllowableValues();
/**
* The lowest possible value of range-based property
*
* @return the lowest possible value of range-based property
*/
int getLowerBound();
/**
* The highest possible value of range-based property
*
* @return the highest possible value of range-based property
*/
int getUpperBound();
/**
* Returns the value object parsed from its string representation and checked against allowable values.
*
* @param value value
* @param exceptionInterceptor exception interceptor
* @return the value object
*/
T parseObject(String value, ExceptionInterceptor exceptionInterceptor);
/**
* Creates instance of ReadableProperty or ModifiableProperty depending on isRuntimeModifiable() result.
*
* @return RuntimeProperty instance
*/
RuntimeProperty<T> createRuntimeProperty();
}Interface for runtime property values.
package com.mysql.cj.conf;
import java.util.Properties;
import javax.naming.Reference;
import com.mysql.cj.exceptions.ExceptionInterceptor;
public interface RuntimeProperty<T> {
PropertyDefinition<T> getPropertyDefinition();
/**
* Explicitly set value of this RuntimeProperty according to the self-titled property value contained in extractFrom.
* This method is called during PropertySet initialization thus ignores the RUNTIME_NOT_MODIFIABLE flag.
* This value will also be the initial one, i.e. resetValue() will reset to this value, not the default one.
* If extractFrom does not contain such property then this RuntimeProperty remains unchanged.
*
* @param extractFrom Properties object containing key-value pairs usually passed from connection string
* @param exceptionInterceptor exception interceptor
*/
void initializeFrom(Properties extractFrom, ExceptionInterceptor exceptionInterceptor);
void initializeFrom(Reference ref, ExceptionInterceptor exceptionInterceptor);
/**
* Reset to initial value (default or defined in connection string/Properties)
*/
void resetValue();
boolean isExplicitlySet();
/**
* Add listener for this property changes.
*
* @param l RuntimePropertyListener
*/
void addListener(RuntimePropertyListener l);
void removeListener(RuntimePropertyListener l);
@FunctionalInterface
public static interface RuntimePropertyListener {
void handlePropertyChange(RuntimeProperty<?> prop);
}
/**
* Get internal value representation as Object.
*
* @return value
*/
T getValue();
/**
* Get initial value (default or defined in connection string/Properties)
*
* @return value
*/
T getInitialValue();
/**
* Get internal value representation as String.
*
* @return value
*/
String getStringValue();
/**
* Set the object value of a property directly. Validation against allowable values will be performed.
*
* @param value value
*/
void setValue(T value);
/**
* Set the object value of a property directly. Validation against allowable values will be performed.
*
* @param value value
* @param exceptionInterceptor exception interceptor
*/
void setValue(T value, ExceptionInterceptor exceptionInterceptor);
}Usage:
// Get property from property set
PropertySet propSet = // ... obtained from connection
RuntimeProperty<Boolean> useSSL = propSet.getBooleanProperty(PropertyKey.useSSL);
System.out.println("useSSL: " + useSSL.getValue());
System.out.println("Explicitly set: " + useSSL.isExplicitlySet());
// Modify property
useSSL.setValue(true);
// Add listener
useSSL.addListener(new RuntimePropertyListener() {
public void handlePropertyChange(RuntimeProperty<?> prop) {
System.out.println("useSSL changed to " + prop.getValue());
}
});
// Get property definition
PropertyDefinition<Boolean> def = useSSL.getPropertyDefinition();
System.out.println("Property: " + def.getName());
System.out.println("Default: " + def.getDefaultValue());
System.out.println("Description: " + def.getDescription());Interface for transforming connection properties.
package com.mysql.cj.conf;
public interface ConnectionPropertiesTransform {
// Transform properties before connection
Properties transformProperties(Properties props);
}Usage:
// Implement custom transform
public class MyPropertiesTransform implements ConnectionPropertiesTransform {
public Properties transformProperties(Properties props) {
// Modify properties as needed
props.setProperty("useSSL", "true");
return props;
}
}
// Use in connection URL
String url = "jdbc:mysql://localhost:3306/mydb" +
"?propertiesTransform=com.mycompany.MyPropertiesTransform";
Connection conn = DriverManager.getConnection(url, "user", "pass");JDBC-specific extension of PropertySet interface.
package com.mysql.cj.jdbc;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.List;
import com.mysql.cj.conf.PropertySet;
public interface JdbcPropertySet extends PropertySet {
/**
* Exposes all ConnectionPropertyInfo instances as DriverPropertyInfo
*
* @return a List of all ConnectionPropertyInfo instances, as DriverPropertyInfo
* @throws SQLException if an error occurs
*/
List<DriverPropertyInfo> exposeAsDriverPropertyInfo() throws SQLException;
}Interface for objects that provide database URLs.
package com.mysql.cj.conf;
public interface DatabaseUrlContainer {
// Get database URL
String getDatabase();
}Enumeration for different views of host lists.
package com.mysql.cj.conf;
public enum HostsListView {
// All hosts
ALL,
// Sources only (for replication)
SOURCES,
// Replicas only (for replication)
REPLICAS;
}Install with Tessl CLI
npx tessl i tessl/maven-com-mysql--mysql-connector-j