Explore MariaDB Connector/J, the official JDBC driver for Java applications to connect to MariaDB and MySQL databases.
MariaDB Connector/J is used to connect applications developed in Java to MariaDB and MySQL databases using the standard JDBC API. The library is LGPL licensed.
MariaDB Connector/J is a Type 4 JDBC driver. It was developed specifically as a lightweight JDBC connector for use with MariaDB and MySQL database servers. It was originally based on the Drizzle JDBC code with numerous additions and bug fixes.
MariaDB Connector/J is compatible with all MariaDB and MySQL server versions.
To determine which MariaDB Connector/J release series would be best to use for each Java version, please see the following table:
Java 17, Java 11, Java 8
MariaDB Connector/J 2.7
JDBC 4.2
↑ see parsec authentication restriction
MariaDB Connector/J can be installed using Maven, Gradle, or by manually putting the .jar
file in your CLASSPATH. See Installing MariaDB Connector/J for more information.
MariaDB Connector/J .jar
files and source code tarballs can be downloaded from the following URL:
JNA (net.java.dev.jna:jna) and JNA-PLATFORM (net.java.dev.jna:jna-platform) 4.2.1 or greater are also needed when you would like to connect to the server with Unix sockets or windows pipes.
The following subsections show the formatting of JDBC connection strings for MariaDB and MySQL database servers. Additionally, sample code is provided that demonstrates how to connect to one of these servers and create a table.
There are two standard ways to get a connection:
The preferred way to get a connection with MariaDB Connector/J is to use the DriverManager class.
When the DriverManager
class is used to locate and load MariaDB Connector/J, the application needs no further configuration. The DriverManager
class will automatically load MariaDB Connector/J and allow it to be used in the same way as any other JDBC driver.
For example:
Connection connection = DriverManager.getConnection("jdbc:mariadb://localhost:3306/DB?user=root&password=myPassword");
MariaDB Connector/J 3.0 only accepts jdbc:mariadb:
as the protocol in connection strings by default. When both MariaDB Connector/J and the MySQL drivers are found in the class-path, using jdbc:mariadb:
as the protocol helps to ensure that Java chooses MariaDB Connector/J.
Connector/J still allows jdbc:mysql:
as the protocol in connection strings when the permitMysqlScheme
option is set. For example:
jdbc:mysql://HOST/DATABASE?permitMysqlScheme
(2.x version did permit connection URLs beginning with both jdbc:mariadb
and jdbc:mysql
)
Another way to get a connection with MariaDB Connector/J is to use a connection pool.
MariaDB Connector/J provides 2 different Datasource pool implementations:
MariaDbDataSource
: The basic implementation. It creates a new connection each time the getConnection()
method is called.
MariaDbPoolDataSource
: A connection pool implementation. It maintains a pool of connections, and when a new connection is requested, one is borrowed from the pool.
The driver's internal pool configuration provides a very fast pool implementation and deals with the issues most of the java pool have:
2 different connection states cleaning after release
deals with non-activity (connections in the pool will be released if not used after some time, avoiding the issue created when the server closes the connection after @wait_timeout is reached).
See the pool documentation for more information.
When using an external connection pool, the MariaDB Driver class org.mariadb.jdbc.Driver
must be configured.
Example using hikariCP JDBC connection pool :
final HikariDataSource ds = new HikariDataSource();
ds.setMaximumPoolSize(20);
ds.setDriverClassName("org.mariadb.jdbc.Driver");
ds.setJdbcUrl("jdbc:mariadb://localhost:3306/db");
ds.addDataSourceProperty("user", "root");
ds.addDataSourceProperty("password", "myPassword");
ds.setAutoCommit(false);
Please note that the driver class provided by MariaDB Connector/J **is not com.mysql.jdbc.Driver
but `org.mariadb.jdbc.Driver!
The org.mariadb.jdbc.MariaDbDataSource
class can be used when the pool datasource configuration only permits the java.sql.Datasource implementation.
The format of the JDBC connection string is:
jdbc:mariadb:[replication:|loadbalance:|sequential:|load-balance-read:]//<hostDescription>[,<hostDescription>...]/[database][?<key1>=<value1>[&<key2>=<value2>]]
HostDescription:
<host>[:<portnumber>] or address=(host=<host>|localSocket=<socket>|pipe=<namedpipe>)[(port=<portnumber>)][(type=(master|replica|slave))][(sslMode=disable|trust|verify-ca|verify-full)]
Some notes about this:
The host must be a DNS name or IP address.
If the host is an IPv6 address, then it must be inside square brackets.
The default port is 3306
.
The default type is master
.
If the failover and load-balancing mode is set to replication
, then the connector assumes that the first host is master, and the others are replicas by default, if their types are not explicitly mentioned.
aurora failover prefix is available on 2.x version.
A detailed host description option supersedes a global option description
sslMode, pipe and localSocket are available since 3.4.1 version
Examples:
localhost:3306
[2001:0660:7401:0200:0000:0000:0edf:bdd7]:3306
somehost.com:3306
address=(host=localhost)(port=3306)(type=master)
The jdbc:mariadb:sequential:address=(localSocket=/socket)(sslMode=disable),10.0.0.1:3306/DB?sslMode=verify-full
connection string will permit to connect to local unix socket if available, or to host 10.0.0.1 using SSL if not.
Failover and Load-Balancing Modes were introduced in MariaDB Connector/J 1.2.0.
Description: This mode supports connection failover in a multi-master environment, such as MariaDB Galera Cluster. This mode does not support load-balancing reads on replicas. The connector will try to connect to hosts in the order in which they were declared in the connection URL, so the first available host is used for all queries.For example, let's say that the connection URL is the following: jdbc:mariadb:sequential:host1,host2,host3/testdb
When the connector tries to connect, it will always try host1 first. If that host is not available, then it will try host2. etc. When a host fails, the connector will try to reconnect to hosts in the same order.
Introduced: 1.3.0
Description: This mode supports connection load-balancing in a multi-master environment, such as MariaDB Galera Cluster. This mode does not support load-balancing reads on replicas. The connector performs load-balancing for all queries by randomly picking a host from the connection URL for each connection, so queries will be load-balanced as a result of the connections getting randomly distributed across all hosts. Before 2.4.2, this option was named failover
- alias still exist for compatibility -
Introduced: 1.2.0
Description: This mode supports connection failover in a primary-replica environment, such as a MariaDB Replication cluster. The mode supports environments with one or more masters. This mode does support load-balancing reads on replicas if the connection is set to read-only before executing the read. The connector performs load-balancing by randomly picking a replica from the connection URL to execute read queries for a connection
Introduced: 1.2.0
Description: When running a multi-master cluster (i.e. Galera), writing to more than one node can lead to optimistic locking errors ("deadlocks"). Writing concurrently to multiple nodes also doesn't bring a whole lot of performance, due to having to (synchronously) replicate to all nodes anyway. This mode supports connection failover in a multi-master environment, such as MariaDB Galera Cluster. This mode does support load-balancing reads on replicas. The connector will try to connect to primary hosts in the order in which they were declared in the connection URL, so the first available host is used for all queries.For example, let's say that the connection URL is the following: jdbc:mariadb:load-balance-read:primary1,primary2,address=(host=replica1)(type=replica),address=(host=replica2)(type=replica)/DB
When the connector tries to connect, it will always try primary1 first. If that host is not available, then it will try primary2. etc. When a primary host fails, the connector will try to reconnect to hosts in the same order.For replica hosts, the connector performs load-balancing for all queries by randomly picking a replica host from the connection URL for each connection, so queries will be load-balanced as a result of the connections getting randomly distributed across all replica hosts.
Introduced: 3.5.1
Description: This mode supports connection failover in an Amazon Aurora cluster. This mode does support load-balancing reads on replica instances if the connection is set to read-only before executing the read. The connector performs load-balancing by randomly picking a replica instance to execute read queries for a connection
Introduced: 1.2.0 and not supported anymore since 3.0 version
driver 3.0 is a complete rewrite of the connector. Specific support for aurora has not been implemented in 3.0, since it relies on pipelining. Aurora is not compatible with pipelining. Issues for Aurora were piling up without the community proposing any PR for them and without access for us to test those modifications. (2.x version has a 5 years support).
See failover description for more information.
General remark: Unknown options are accepted and silently ignored.
The following options are currently supported.
Description: User name.
Data Type: string
Default Value: null
Introduced: 1.0.0
Description: password
Data Type: string
Default Value: null
Introduced: 1.0.0
Description: The connect timeout value, in milliseconds, or zero for no timeout
Data Type: integer
Default Value: 30 000
Introduced: 1.1.8
Description: Text (default) is a globaly a safe default behavior, always working without issue. Binary protocol (useServerPrepStmts=true) has usually good benefits, but that depends: if missing cache, it will have an overhead of preparing before execution. If hitting cache, this perform better, but difference usually isn't huge, because most of the queries have simple execution plan. This is totally depending on queries, but to have some order of difference, here is some realistic differences : missing cache : 50% performance loss / hitting cache: 5-10% performance gain (because simple execution plan). Another thing to consider : Since MariaDB 10.6 Server with MDEV-19237, server now permits to avoid resending metadata when they haven't changed when enabling useServerPrepStmts option (This concerns SQL commands that return a result-set). This avoids useless information transiting on the network and parsing those metadata, and that permit huge gain (around 10-30% depending on query, metadata can be huge compare to resultset data). So, if you use a MariaDB server version 10.6, and application doesn't execute completly differents queries, binary protocol (option 'useServerPrepStmts') is recommended.
Data Type: boolean
Default Value: false
Introduced: 1.3.0
Description: Permit loading data from file. see LOAD DATA LOCAL INFILE. Having this option enable can impact batch performance. Disabling it can permit some batch improvement
Data Type: boolean
Default Value: true
Introduced: 1.2.1
more information on Using TLS/SSL with MariaDB java connector
Description: Enables SSL/TLS in a specific mode. this option replaces the deprecated options: disableSslHostnameVerification, trustServerCertificate, useSsl
Data Type: string
Default Value: disable
Valid Values:
disable: Do not use SSL/TLS (alias 'false', '0')
trust: Only use SSL/TLS for encryption. Do not perform certificate or hostname verification. (alias 'required')
verify-ca: Use SSL/TLS for encryption and perform certificates verification, but do not perform hostname verification. (alias 'verify_ca')
verify-full: Use SSL/TLS for encryption, certificate verification, and hostname verification (alias 'verify_identity', 'true', '1')
Introduced: 3.0.0
Description: |Permits providing server's certificate in DER form, or server's CA certificate. The server will be added to trustStore. This permits a self-signed certificate to be trusted.Can be used in one of 3 forms : * serverSslCert=/path/to/cert.pem (full path to certificate)* serverSslCert=classpath:relative/cert.pem (relative to current classpath)* or as verbatim DER-encoded certificate string "------BEGIN CERTIFICATE-----"
Data Type: boolean
Default Value: false
Introduced: 1.1.0
Description: File path of the keyStore file that contain client private key store and associate certificates (similar to java System property "javax.net.ssl.keyStore", but ensure that only the private key's entries are used).
Data Type: string
Default Value: null
Alias: clientCertificateKeyStoreUrl
Introduced: 1.1.1
Description: Password for the client certificate keyStore (similar to java System property "javax.net.ssl.keyStorePassword")
Data Type: string
Default Value: null
Alias: clientCertificateKeyStorePassword
Introduced: 1.3.4
Description: Force TLS/SSL cipher (comma separated list). Example : "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"
Data Type: string
Default Value: use JRE ciphers
Introduced: 1.5.0
Description: Force TLS/SSL protocol to a specific set of TLS versions (comma separated list). Example : "TLSv1,TLSv1.1,TLSv1.2
Data Type: string
Default Value: use JRE default
Alias: enabledSSLProtocolSuites
Introduced: 1.5.0
Description: deprecated, use sslMode insteadWhen using ssl, the driver checks the hostname against the server's identity as presented in the server's certificate (checking alternative names or the certificate CN) to prevent man-in-the-middle attacks. This option permits deactivating this validation. Hostname verification is disabled when the trustServerCertificate option is set
Data Type: boolean
Default Value: false
Introduced: 2.1.0
Deprecated: 3.0.0
Description: deprecated, use sslMode instead Force SSL/TLS on connection(useSSL can be used as alias).
Data Type: boolean
Default Value: false
Introduced: 1.1.0
Deprecated: 3.0.0
Description: deprecated, use sslMode instead When using SSL/TLS, do not check server's certificate
Data Type: boolean
Default Value: false
Introduced: 1.1.1
Deprecated: 3.0.0
See the pool documentation for pool configuration.
Description: Use pool. This option is useful only if not using a DataSource object, but only a connection object
Data Type: boolean
Default Value: false
Introduced: 2.2.0
Description: Pool name that permits identifying threads.default: auto-generated as MariaDb-pool-
Data Type: string
Default Value: MariaDB-pool
Introduced: 2.2.0
Description: The maximum number of physical connections that the pool should contain
Data Type: integer
Default Value: 8
Introduced: 2.2.0
Description: When connections are removed due to not being used for longer than "maxIdleTime", connections are closed and removed from the pool. "minPoolSize" indicates the number of physical connections the pool should keep available at all times. Should be less or equal to maxPoolSize.
Data Type: integer
Default Value: maxPoolSize value
Introduced: 2.2.0
Description: When asking a connection to pool, the pool will validate the connection state. "poolValidMinDelay" permits disabling this validation if the connection has been borrowed recently avoiding useless verifications in case of frequent reuse of connections. 0 means validation is done each time the connection is asked. In milleseconds.
Data Type: integer
Default Value: 1000
Introduced: 2.2.0
Description: The maximum amount of time in seconds that a connection can stay in the pool when not used. This value must always be below @wait_timeout value - 45s
Data Type: integer
Default Value: 600
minimum value is 60 seconds
Introduced: 2.2.0
Description: When a connection is closed() (given back to pool), the pool resets the connection state. Setting this option, the prepare command will be deleted, session variables changed will be reset, and user variables will be destroyed when the server permits it (>= MySQL 5.7.3), permitting saving memory on the server if the application make extensive use of variables
Data Type: boolean
Default Value: false
Introduced: 2.2.0
Description: Register JMX monitoring pools
Data Type: boolean
Default Value: true
Introduced: 2.2.0
Description: File path of the trustStore file (similar to java System property "javax.net.ssl.trustStore"). (legacy alias trustCertificateKeyStoreUrl)Use the specified file for trusted root certificates.When set, overrides serverSslCert. (see trustStorePassword in case if a jks truststore with a password)
Data Type: string
Default Value: null
Introduced: 3.5.0 (or 1.3.4 in 1.x, 2.0.0 in 2.x)
Description: Password for the trusted root certificate file (similar to java System property "javax.net.ssl.trustStorePassword").(legacy alias trustCertificateKeyStorePassword).
Data Type: string
Default Value: null
Introduced: 3.5.0 (or 1.3.4 in 1.x, 2.0.0 in 2.x)
Description: Indicate trust store type (JKS/PKCS12). default is null, then using java default type.(legacy alias trustCertificateKeystoreType).
Data Type: string
Default Value: null
Introduced: 3.5.0 (or 2.4.0 in 2.x)
Description: databaseMetaData.getDatabaseProductName() return "MariaDB" or "MySQL" according to server type
Data Type: boolean
Default Value: false
Introduced: 2.4.0
Description: permits to restrict authentication plugins (comma separated). For example, the following connection string only allows the mysql_native_password and client_ed25519 client authentication plugins:jdbc:mariadb:HOST/DATABASE?restrictedAuth=mysql_native_password,client_ed25519
. If not set, permit all authentication plugins.
Data Type: string
Default Value: null
Introduced: 3.0.0
Description: Only the first characters corresponding to this options size will be displayed in logs
Data Type: integer
Default Value: 1024
Introduced: 1.5.0
Description: permit multi-queries like insert into ab (i) values (1); insert into ab (i) values (2)
.
Data Type: boolean
Default Value: false
Introduced: 1.0.0
Description: If set to 'true', an exception is thrown during query execution containing a query string. This is useful in development, but can lead to security issue if logs are available.
Data Type: boolean
Default Value: false
Introduced: 1.1.0
Description: Compresses the exchange with the database through gzip. This permits better performance when the database is not in the same location.
Data Type: boolean
Default Value: false
Introduced: 1.0.0
Description: to use a custom socket factory, set it to the full name of the class that implements javax.net.SocketFactory
Introduced: 1.1.0
Description: Sets corresponding option on the connection socket. Default to true since 3.0.0 (was false before)
Data Type: boolean
Default Value: true
Introduced: 1.0.0
Description: This option can be used in environments where connections are created and closed in rapid succession. Often, it is not possible to create a socket in such an environment after a while, since all local "ephemeral" ports are used up by TCP connections in TCP_WAIT state. Using tcpAbortiveClose works around this problem by resetting TCP connections (abortive or hard close) rather than doing an orderly close. It is accomplished by using socket.setSoLinger(true,0) for abortive close.
Data Type: boolean
Default Value: false
Introduced: 1.1.1
Description: On Windows, specify named pipe name to connect (windows equivalent of unix socket)
Data Type: string
Default Value: null
Introduced: 1.1.3
Description: Datatype mapping flag, handle MySQL Tiny as BIT(boolean).
Data Type: boolean
Default Value: true
Introduced: 1.0.0
Description: returns Year as date type, rather than numerical.
Data Type: boolean
Default Value: true
Introduced: 1.0.0
Description: = pairs separated by comma, mysql session variables, set upon establishing successful connection.
Data Type: string
Default Value: null
Introduced: 1.1.4
Description: Permits connecting to the database via Unix domain socket, if the server allows it. The value is the path of Unix domain socket (i.e "socket" database parameter : select @@socket) .
Data Type: string
Default Value: null
Introduced: 1.1.4
Description: Hostname or IP address to bind the connection socket to a local (UNIX domain) socket.
Data Type: string
Default Value: null
Introduced: 1.1.7
Description: Defined the network socket timeout (SO_TIMEOUT) in milliseconds. Value of 0 disables this timeout. If the goal is to set a timeout for all queries, the server has permitted a solution to limit the query time by setting a system variable, max_statement_time. The advantage is that the connection then is still usable.
Data Type: integer
Default Value: 0
Introduced: 1.1.7
Description: Defined the network socket timeout (SO_TIMEOUT) in milliseconds. Value of 0 disables this timeout. If the goal is to set a timeout for all queries, the server has permitted a solution to limit the query time by setting a system variable, max_statement_time. The advantage is that the connection then is still usable.
Data Type: integer
Default Value: 0
Introduced: 1.1.7
Description: the specified database in the url will be created if nonexistent.
Data Type: boolean
Default Value: false
Introduced: 1.1.7
Description:enable/disable callable Statement cache
Data Type: boolean
Default Value: true
Introduced: 1.4.0
Description: When performance_schema is active, permit to send server some client information in a key;value pair format (example: connectionAttributes=key1:value1,key2,value2).Those informations can be retrieved on server within tables performance_schema.session_connect_attrs and performance_schema.session_account_connect_attrs.This can permit from server an identification of client/application
Data Type: string
Default Value: null
Introduced: 1.4.0
Description: Not compatible with aurora*During connection, different queries are executed. When option is active those queries are send using pipeline (all queries are send, then only all results are reads), permitting faster connection creation.
Data Type: boolean
Default Value: true
Introduced: 1.6.0
Description: Set default autocommit value on connection initialization.
Data Type: boolean
Default Value: true
Introduced: 2.2.0
Description: Usually, Connection.isValid just send an empty packet to server, and server send a small response to ensure connectivity. When this option is set, connector will ensure Galera server state "wsrep_local_state" correspond to allowed values (separated by comma). example "4,5", recommended is "4". see galera state to know more
Data Type: string
Default Value: null
Introduced: 2.2.5
Description: add "SHOW ENGINE INNODB STATUS" result to exception trace when having a deadlock exception.
Data Type: boolean
Default Value: false
Introduced: 2.3.0
Description: add thread dump to exception trace when having a deadlock exception.
Data Type: boolean
Default Value: false
Introduced: 2.3.0
Description: Use a buffered inputSteam that read socket available data
Data Type: boolean
Default Value: true
Introduced: 2.4.0
Description: When using GSSAPI authentication, use this value as the Service Principal Name (SPN) instead of the one defined for the user account on the database server.
Data Type: string
Default Value: null
Introduced: 2.4.0
Description: force DatabaseMetadata.getDatabaseProductName() to return "MySQL" as database, not real database type.
Data Type: boolean
Default Value: false
Introduced: 2.4.1
Description: The driver will call setFetchSize(n) with this value on all newly-created Statements
Data Type: integer
Default Value: 0
Introduced: 2.4.2
Description: Resultset metadata getTableName always return blank. This option is mainly for ORACLE db compatibility.
Data Type: boolean
Default Value: false
Introduced: 2.4.3
Description: Indicate path to RSA server public key file for sha256_password and caching_sha2_password authentication password
Data Type: string
Default Value: null
Introduced: 2.5.0
Description: Authorize client to retrieve RSA server public key when serverRsaPublicKeyFile is not set (for sha256_password and caching_sha2_password authentication password)
Data Type: boolean
Default Value: false
Introduced: 2.5.0
Description: Indicate the TLS org.mariadb.jdbc.tls.TlsSocketPlugin plugin type to use. Plugin must be present in classpath
Data Type: string
Default Value: null
Introduced: 2.5.0
Description: Indicate the credential plugin type to use. Plugin must be present in classpath
Data Type: string
Default Value: null
Introduced: 2.5.0
Description: Permit to set socket option TCP_KEEPCOUNT (only if java 11+)
Data Type: integer
Default Value: 0
Introduced: 3.0.0
Description: Permit to set socket option TCP_KEEPIDLE (only if java 11+)
Data Type: integer
Default Value: 0
Introduced: 3.0.0
Description: Permit to set socket option TCP_KEEPINTERVAL (only if java 11+)
Data Type: integer
Default Value: 0
Introduced: 3.0.0
Description: when added to connection string, permit jdbc:mysql:
prefix in connection string
Data Type: boolean
Default Value: false
Introduced: 3.0.0
Description: When useServerPrepStmts is enabled, any positive value indicates that a prepared statement cache of the specified size will be used. If the value is less than or equal to zero, the cache will not be enabled. Before 3.0, an option cachePrepStmts was indicatin if cache has to be enable
Data Type: integer
Default Value: 250
Introduced: 1.3.0
Description: Enables transaction caching. If a failover occurs before a transaction is committed or rolled back, the transaction's cached statements are re-executed on the new primary server. Connector/J requires that applications only use idempotent queries. If the number of statements in the transaction cache exceeds transactionReplaySize, caching will be disabled until the transaction is committed or rolled back.
Data Type: boolean
Default Value: false
Introduced: 3.0.0
Description: Sets the number of statements that should be saved in the transaction cache when transactionReplay is enabled.
Data Type: integer
Default Value: 64
Introduced: 3.0.0
Description: Use dedicated COM_STMT_BULK_EXECUTE protocol for batch insert when possible. (batch without Statement.RETURN_GENERATED_KEYS and streams) to have faster batch.
Data Type: boolean
Default Value: true
Introduced: 3.0.0 (was false since version >= 2.3.0)
Description: |"schema" and "database" are server synonymous. Connector historically get/set database using Connection.setCatalog()/getCatalog(), setSchema()/getSchema() being no-op. Setting option useCatalogTerm to "schema" will change that behavior to use Schema in place of Catalog. Affected changes : database change will be done with either Connection.setCatalog()/getCatalog() or Connection.setSchema()/getSchema(), 2: DatabaseMetadata methods that use catalog or schema filtering, 3: ResultsetMetadata getCatalogName/getSchemaName
Data Type: string
Default Value: CATALOG
Introduced: 3.2.0
Description: for connector 2.x compatibility only, getGeneratedKeys() will then returns all ids of multi-value inserts. This is not compatible with galera servers
Data Type: boolean
Default Value: false
Introduced: 3.3.2
Description: When set, commands with a specific XID will reuse previous connection used for this XID.
Data Type: boolean
Default Value: false
Introduced: 3.4.1
Description: Connector force utf8mb4 charset at connection. Indicate what utf8mb4 collation to use if set. if not set, server default collation for utf8mb4 will be used.Useful only for server before MariaDB 11.4, because then a better solution would be to set character_set_collations
Data Type: string
Default Value: null
Introduced: 3.5.0
Description: On connection creation, indicate behavior when password is expired. When true (default) throw an expired password error. When false, connection succeed in "sandbox" mode, only queries related to password change are allowed.
Data Type: boolean
Default Value: true
Introduced: 3.5.2
Description: Indicate if Statement/PreparedStatement.executeQuery for command that produce no result will return an exception or just an empty result-set. When enabled, command not returning no data will end returning an empty result-set, when disabled, command not returning no data will end throwing an exception
Data Type: boolean
Default Value: true
Introduced: 3.5.2
Description: When enable, Timestamps string representation will be compatible with 2.7's behavior (fractional part will only be displayed if required, not according to timestamp precision) .
Data Type: boolean
Default Value: false
Introduced: 3.5.3
Description: permit to enable/disable caching of codecs (FIELD encoder/decoder).
Data Type: boolean
Default Value: false
Introduced: 3.5.4
Description: Possible implementation DatabaseMetadata.getExportedKey. Either use INFORMATION_SCHEMA or SHOW CREATE TABLE to retrieve metadata information. When set to "auto", the method will automatically choose between the INFORMATION_SCHEMA approach or the SHOW CREATE implementation based on whether the database server is running locally or remotely. Possible values: "UseInformationSchema", "UseShowCreate", or "auto".
Data Type: string
Default Value: auto
Introduced: 3.5.4
allowMasterDownConnection
When the replication Failover and Load Balancing Mode is in use, allow the creation of connections when the master is down. If no masters are available, then the default connection will be a replica, and Connection.isReadOnly() will return true. Default: false. Since 2.2.0, removed in 3.0.0
interactiveClient
Session timeout is defined by the wait_timeout server variable. Setting interactiveClient to true will tell the server to use the interactive_timeout server variable.Default: false. Since 1.1.7
assureReadOnly
When this parameter enabled when a Failover and Load Balancing Mode is in use, and a read-only connection is made to a host, assure that this connection is in read-only mode by setting the session to read-only.Default to false.Since 1.3.0, removed in 3.0.0
autoReconnect
If this parameter is enabled and Failover and Load Balancing Mode is not in use, the connector will simply try to reconnect to its host after a failure. This is referred to as Basic Failover. If this parameter is enabled and Failover and Load Balancing Mode is in use, the connector will blacklist the failed host and try to connect to a different host of the same type. This is referred to as Standard Failover. Default is false.since 1.1.7, removed in 3.0.0
cachePrepStmts
if useServerPrepStmts = true, cache the prepared informations in a LRU cache to avoid re-preparation of command. Next use of that command, only prepared identifier and parameters (if any) will be sent to server. This mainly permit for server to avoid reparsing query. Default: true. Since 1.3.0, removed in 3.0.0
callableStmtCacheSize
This sets the number of callable statements that the driver will cache per VM if "cacheCallableStmts" is enabled.Default: true. Since 1.4.0, removed in 3.0.0
enablePacketDebug
Driver will save the last 16 MySQL packet exchanges (limited to first 1000 bytes). Hexadecimal value of those packets will be added to stacktrace when an IOException occur.This option has no impact on performance but driver will then take 16kb more memory.Default: false. Since 1.6.0, 2.0.1, removed in 3.0.0
failoverLoopRetries
When the connector is searching silently for a valid host, this parameter defines the maximum number of connection attempts the connector will make before throwing an exception.This parameter differs from the "retriesAllDown" parameter because this silent search is used in situations where the connector can temporarily workaround the problem, such as by using the master connection to execute reads when the replica connection fails.Default: 120.since 1.2.0, removed in 3.0.0
jdbcCompliantTruncation
Truncation error ("Data truncated for column '%' at row %", "Out of range value for column '%' at row %") will be thrown as an error, and not as a warning.Default: true. Since 1.4.0
keyPassword
Password for the private key in client certificate keyStore. (only needed if private key password differ from keyStore password).Since 1.5.3, removed in 3.0.0
loadBalanceBlacklistTimeout
When a connection fails, this host will be blacklisted for the amount of time defined by this parameter.When connecting to a host, the driver will try to connect to a host in the list of non-blacklisted hosts and, only if none are found, attempt blacklisted ones.This blacklist is shared inside the classloader.Default: 50 seconds.since 1.2.0, removed in 3.0.0
log
Enable log information. require Slf4j version > 1.4 dependency.Log level correspond to Slf4j logging implementationDefault: false. Since 1.5.0, removed in 3.0.0
passwordCharacterEncoding
Indicate password encoding charset. Charset value must be a Java charset. Example : "UTF-8" Default: null (= platform's default charset) . Since 1.5.9, removed in 3.0.0
prepStmtCacheSqlLimit
if useServerPrepStmts = true, defined queries larger than this size will not be cached. Default: 2048. Since 1.3.0
profileSql
log query execution time.Default: false. Since 1.5.0, removed in 3.0.0
slowQueryThresholdNanos
Will log query with execution time superior to this value (if defined )Default: 1024. Since 1.5.0, removed in 3.0.0
retriesAllDown
When the connector is performing a failover and all hosts are down, this parameter defines the maximum number of connection attempts the connector will make before throwing an exception.Default: 120 seconds.since 1.2.0, removed in 3.0.0
rewriteBatchedStatements
For insert queries, rewrite batchedStatement to execute in a single executeQuery.example:insert into ab (i) values (?) with first batch values = 1, second = 2 will be rewritteninsert into ab (i) values (1), (2). If query cannot be rewriten in "multi-values", rewrite will use multi-queries : INSERT INTO TABLE(col1) VALUES (?) ON DUPLICATE KEY UPDATE col2=? with values [1,2] and [2,3]" will be rewrittenINSERT INTO TABLE(col1) VALUES (1) ON DUPLICATE KEY UPDATE col2=2;INSERT INTO TABLE(col1) VALUES (3) ON DUPLICATE KEY UPDATE col2=4when active, the useServerPrepStmts option is set to falseDefault: false. Since 1.1.8, removed in 3.0.0
serverTimezone
Defines the server time zone.to use only if the jre server has a different time implementation of the server.(best to have the same server time zone when possible).since 1.1.7, removed in 3.0.0
sharedMemory
Permits connecting to the database via shared memory, if the server allows it. The value is the base name of the shared memory.since 1.1.4, removed in 3.0.0
staticGlobal
Indicates the values of the global variables max_allowed_packet, wait_timeout, autocommit, auto_increment_increment, time_zone, system_time_zone and tx_isolation) won't be changed, permitting the pool to create new connections faster.Default: false. Since 2.2.0, removed in 3.0.0
tcpNoDelay
Sets corresponding option on the connection socket.since 1.0.0, removed in 3.0.0
tcpRcvBuf
set buffer size for TCP buffer (SO_RCVBUF).since 1.0.0, removed in 3.0.0
tcpSndBuf
set buffer size for TCP buffer (SO_SNDBUF).since 1.0.0, removed in 3.0.0
trackSchema
Permit to disabled "session_track_schema" setting when server has CLIENT_SESSION_TRACK capabilityDefault: True. Since 2.5.4, removed in 3.0.0
useBatchMultiSend
Not compatible with aurora Driver will can send queries by batch. If set to false, queries are sent one by one, waiting for the result before sending the next one. If set to true, queries will be sent by batch corresponding to the useBatchMultiSendNumber option value (default 100) or according to the max_allowed_packet server variable if the packet size does not permit sending as many queries. Results will be read later, avoiding a lot of network latency when the client and server aren't on the same host. This option is mainly effective when the client is distant from the server. More information hereDefault: true (false if using aurora failover) . Since 1.5.0, removed in 3.0.0
useBatchMultiSendNumber
When option useBatchMultiSend is active, indicate the maximum query send in a row before reading results.Default: 100. Since 1.5.0
useFractionalSeconds
Correctly handle subsecond precision in timestamps (feature available with MariaDB 5.3 and later).May confuse 3rd party components (Hibernated).Default: true. Since 1.0.0
useOldAliasMetadataBehavior
Metadata ResultSetMetaData.getTableName() returns the physical table name. "useOldAliasMetadataBehavior" permits activating the legacy code that sends the table alias if set. Default: false. Since 1.1.9
validConnectionTimeout
When multiple hosts are configured, the connector verifies that the connections haven't been lost after this much time in seconds has elapsed.When this parameter is set to 0, no verification will be done. Default:120 secondssince 1.2.0, removed in 3.0.0
GSSAPI in windows isn't well supported in java, causing recurrent issues. Since 3.1, waffle-jna is marked as a dependency to provide good GSSAPI support without problems. This has the drawback to make connector and dependencies to a size of around 4Mb.
If size is important, the dependency can be removed, the connector working great, just will have some limitation using GSSAPI on windows :
this can be done like this:
using maven
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.1.0</version>
<exclusions>
<exclusion>
<groupId>com.github.waffle</groupId>
<artifactId>waffle-jna</artifactId>
</exclusion>
</exclusions>
</dependency>
using graddle:
dependencies {
implementation('org.mariadb.jdbc:mariadb-java-client:3.1.0') {
exclude group: 'com.github.waffle', module: 'waffle-jna'
}
}
Since 3.5.1, parsec authentication is implemented in connector. This requires java 15+ (to use java native ed25519 Algorithm implementation).
In order to use parsec authentication with previous version of java, BouncyCastle is required as dependency:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk18on</artifactId>
<version>1.78.1</version>
</dependency>
The simplest approach to avoid time zone headaches is for the client and server to operate in the same time zone.
There are 3 options that control timestamps behavior in the java connector:
connectionTimeZone: (LOCAL | SERVER | ) - This option defines the connection's time zone. LOCAL retrieves the JVM's default time zone, SERVER fetches the server's global time zone upon connection creation, and allows specifying a server time zone without requesting it during connection establishment.
forceConnectionTimeZoneToSession: (true | false) - This setting dictates whether the connector enforces the connection time zone for the session.
preserveInstants: (true | false) - This option controls whether the connector converts Timestamp values to the connection's time zone.
By default, the connector adopts the JVM's default time zone. If the client and server reside in different time zones, it's recommended to configure the connection time zone to match the JVM's default by setting forceConnectionTimeZoneToSession to true. This ensures proper operation of time functions.
(This isn’t the default behavior because there is a server Requirements to set tzinfo depending on the JVM's time zones)
Just like Java's Instant and LocalDateTime, server-side TIMESTAMP and DATETIME fields serve distinct purposes. One represents a specific point in time (a moment), while the other doesn't.
TIMESTAMP: This represents an exact moment on the timeline, expressed using the connection's time zone. When stored, it gets converted to UTC (Coordinated Universal Time) for consistency. Upon retrieval, it's converted back to the connection's time zone for display.
DATETIME: This combines date and time-of-day information but doesn't represent a specific moment.
Due to its wider range, DATETIME is sometimes mistakenly used to store a specific point in time. While this might work if the client and server share the same time zone, it creates problems when they differ.
While using DATETIME instead of TIMESTAMP is generally discouraged, a specific combination of settings ("preserveInstants=true&connectionTimeZone=SERVER") can force all Java Timestamp exchanges to be converted to the connection's time zone during storage and retrieval. However, this approach is not recommended for long-term solutions.
The MariaDB Connector/J versions before 3.4 offered a single "timezone" option. While this functionality remains compatible, it's now separated into two distinct settings: connectionTimeZone and forceConnectionTimeZoneToSession. Here's a breakdown of how the old option translates to the new ones: "timezone=America/Los_Angeles" is equivalent to "connectionTimeZone=America/Los_Angeles&forceConnectionTimeZone=true
To mimic the behavior of the "useLegacyDatetimeCode=false" option from MariaDB 2.x, you can set the following combination: “connectionTimeZone=SERVER&preserveInstants=true”
Note: Unlike the MySQL Connector, the MariaDB Connector/J defaults connectionTimeZone to LOCAL (JVM's default) instead of SERVER.
The fastest way to load lots of data is using LOAD DATA INFILE. However, using "LOAD DATA LOCAL INFILE" (ie: loading a file from the client) may be a security problem if someone can execute a query from the client, he can have access to any file on the client (according to the rights of the user running the client process).
A specific option "allowLocalInfile" (default to true) can disable this functionality on the client side. The global variable local_infile can disable LOAD DATA LOCAL INFILE on the server side.
You can provide custom stream as well using a specific setLocalInfileInputStream
Statement statement = connection.createStatement();
org.mariadb.jdbc.Statement mariaDbStatement =
statement.unwrap(org.mariadb.jdbc.Statement.class);
mariaDbStatement.setLocalInfileInputStream(in);
String sql =
"LOAD DATA LOCAL INFILE 'notUsed'"
+ " INTO TABLE myTable "
+ " FIELDS TERMINATED BY '\\t' ENCLOSED BY ''"
+ " ESCAPED BY '\\\\' LINES TERMINATED BY '\\n'";
statement.execute(sql);
Contrary to mysql connector, setLocalInfileInputStream value can only be used for next execution.
Driver follow the JDBC specifications, permitting Statement.setQueryTimeout() for a particular statement.
If the goal is to set a timeout for all queries, the server permits a limiting query time by setting the system variable max_statement_time.
This solution will handle query timeout better (and faster) than java solutions (JPA2, "javax.persistence.query.timeout", Pools integrated solution like tomcat jdbc-pool "queryTimeout"...).
Option "sessionVariables" permit to set this system variable easily : Example :
#will set a maximum query timeout of 10 seconds for this connection
jdbc:mariadb://localhost/db?user=user&sessionVariables=max_statement_time=10
By default, Statement.executeQuery()
will read the full result set from the server.
With large result sets, this will require large amounts of memory.
To avoid using too much memory, rather use Statement.setFetchSize(int numberOfRowInMemory) to indicate the number of rows that will be stored in memory
Example :
using Statement.setFetchSize(1000)
indicates that 1000 rows will be stored in memory.
So, when the query has executed, 1000 rows will be in memory. After 1000 ResultSet.next()
, the next 1000 rows will be stored in memory, and so on.
If another query is run on same connection while the resultset has not been completly read, the connector will fetch all remaining rows before executing the query. This can lead to still needing lots of memory. Recommendation is then to use another connection for simultaneous operations.
Note that the server usually expects clients to read off the result set relatively quickly. The net_write_timeout server variable controls this behavior (defaults to 60s). If you don't expect results to be handled in this amount of time there is a different possibility:
With you can use the query "SET STATEMENT net_write_timeout=10000 FOR XXX" with XXX your "normal" query. This will indicate that specifically for this query, net_write_timeout will be set to a longer time (10000 in this example).
for older servers, a specific query will have to temporarily set net_write_timeout ("SET STATEMENT net_write_timeout=..."), and set it back afterward.
if your application usually uses a lot of long queries with fetch size, the connection can be set using option "sessionVariables=net_write_timeout=xxx"
Even using setFetchSize, the server will send all results to the client.
If another query is executed on the same connection when a streaming resultset has not been fully read, the connector will put the whole remaining streaming resultset in memory in order to execute the next query. This can lead to OutOfMemoryError if not handled.
Before version 1.4.0, the only accepted value for fetch size was Statement.setFetchSize(Integer.MIN_VALUE)
(equivalent to Statement.setFetchSize(1)
). This value is still accepted for compatilibity reasons but rather use Statement.setFetchSize(1)
, since according to JDBC the value must be >= 0.
The driver uses server prepared statements as a standard to communicate with the database (since 1.3.0). If the "allowMultiQueries" options are set to true, the driver will only use text protocol. Prepared statements (parameter substitution) is handled by the driver, on the client side.
Callable statement implementation won't need to access stored procedure metadata (mysql.proc) table if both of following are true
CallableStatement.getMetadata() is not used
Parameters are accessed by index, not by name
When possible, following the two rules above provides both better speed and eliminates concerns about SELECT privileges on themysql.proc table.
Java permit retrieving last generated keys,using Statement.getGeneratedKeys().
Example:
Statement stmt = sharedConn.createStatement();
stmt.execute(
"INSERT INTO executeGenerated(t2) values (100)", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
System.out.println(rs.getInt(1));
Only the first generated key will be returned, meaning that for multi-insert the generated key retrieved will correspond to the first generated value of the command.
If retrieving all generated values for multiple insert is needed, please use INSERT...RETURNING command (since MariaDB 10.5).
The following optional interfaces are implemented by the org.mariadb.jdbc.MariaDbDataSource class : javax.sql.DataSource, javax.sql.ConnectionPoolDataSource, javax.sql.XADataSource
careful : org.mariadb.jdbc.MySQLDataSource doesn't exist anymore and should be replaced with org.mariadb.jdbc.MariaDbDataSource since v1.3.0
The following code provides a basic example of how to connect to a MariaDB or MySQL server and create a table.
Connection connection = DriverManager.getConnection("jdbc:mariadb://localhost:3306/test", "username", "password");
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE a (id int not null primary key, value varchar(20))");
stmt.close();
connection.close();
The driver implements 3 kinds of services:
Credential service: permit giving credential
Authentication service: permit adding client authentication plugins.
SSL factory service: custom TSL implementation
Credentials are usually set using user/password in the connection string or by using DriverManager.getConnection(String url, String user, String password).
Credential plugins permit to provide credential information from other means. Those plugins have to be activated setting option credentialType
to designated plugin.
The driver has 3 default plugins :
This permits AWS database IAM authentication. The plugin generate a token using IAM credential and region. Token is valid for 15 minutes and cached for 10 minutes.
To use this credential authentication, com.amazonaws:aws-java-sdk-rds dependency must be registred in classpath. Implementation use SDK DefaultAWSCredentialsProviderChain and DefaultAwsRegionProviderChain to get IAM credential and region. see DefaultAWSCredentialsProviderChain and DefaultAwsRegionProviderChain to check how those information can be retrieved (environment variable / system properties, files, ...)
Example: jdbc:mariadb://host/db?credentialType=AWS-IAM&useSsl&serverSslCert=/somepath/rds-combined-ca-bundle.pem
with AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_REGION environment variable set.
User and Password are retrieved from environment variables. default environment variables are MARIADB_USER and MARIADB_PWD, but can be changed by setting additional option userKey
and pwdKey
Example : using connection string jdbc:mariadb://host/db?credentialType=ENV
user and password will be retrieved from environment variable MARIADB_USER and MARIADB_PWD.
User and Password are retrieved from java properties. default property name are mariadb.user and mariadb.pwd, but property names can be changed by setting additional option userKey
and pwdKey
Example : using connection string jdbc:mariadb://host/db?credentialType=PROPERTY&userKey=mariadbUser&pwdKey=mariadbPwd
user and password will be retrieved from java properties mariadbUser
and mariadbPwd
Client authentication plugins are now defined as services. This permits to easily add new client authentication plugins.
List of authentication plugins in java connector :
mysql_clear_password
auth_gssapi_client
client_ed25519
mysql_native_password
mysql_old_password
dialog (PAM)
sha256_password
caching_sha2_password
New authentication plugins can be created implementing interface org.mariadb.jdbc.authentication.AuthenticationPlugin, and listing new plugin in a META-INF/services/org.mariadb.jdbc.authentication.AuthenticationPlugin file.
Custom SSL implementation can be used implementing A connection to a server initially creates a socket. When set, SSL socket is layered over this existing socket. Implementing org.mariadb.jdbc.tls.TlsSocketPlugin permit to provide custom SSL implementation for example create a new HostnameVerifier implementation.
Custom implementation need to implement org.mariadb.jdbc.tls.TlsSocketPlugin and register service META-INF/services/org.mariadb.jdbc.tls.TlsSocketPlugin
Custom implementation are activated using option tlsSocketType
In MariaDB Connector/J 3.0, logging can now be enabled at runtime. Connector/J uses the slf4j API if it is installed. Otherwise, Connector/J uses the JDK logger / console.
logger name is "org.mariadb.jdbc".
Connector/J supports the following Java logging levels:
INFO
Logs connection errors
DEBUG/FINE
Logs SQL statements
TRACE/FINEST
Logs network exchanges
Be careful with "trace" level, purpose is to log all exchanges with server. This means huge amount of data. Bad configuration can lead to problems, like quickly filling the disk.
Example of configuring "trace" level on driver for logback: file logback.xml in src/main/resources/
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="org.mariadb.jdbc" level="trace" additivity="false">
<appender-ref ref="STDOUT"/>
</logger>
<root level="error">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
Exemple of generated logs :
11:47:04.613 [main] TRACE o.m.j.c.socket.impl.PacketWriter - send: conn=17532 (M)
+--------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------------------------------------------------+------------------+
| 09 00 00 00 03 53 45 4C 45 43 54 20 31 | .....SELECT 1 |
+--------------------------------------------------+------------------+
11:47:04.613 [main] TRACE o.m.j.c.socket.impl.PacketReader - read: conn=17532 (M)
+--------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------------------------------------------------+------------------+
| 01 00 00 01 01 | ..... |
+--------------------------------------------------+------------------+
11:47:04.613 [main] TRACE o.m.j.c.socket.impl.PacketReader - read: conn=17532 (M)
+--------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------------------------------------------------+------------------+
| 18 00 00 02 03 64 65 66 00 00 00 01 31 00 00 0C | .....def....1... |
| 3F 00 01 00 00 00 03 81 00 00 00 00 | ?........... |
+--------------------------------------------------+------------------+
For MariaDB Connector/J's continuous integration and automated test results, please see MariaDB Connector/J's Travis CI.
If you find a bug, please report it via the CONJ project on MariaDB's Jira bug tracker.
The source code is available at the mariadb-connector-j repository on GitHub.
GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
For licensing questions, see the Licensing FAQ.
Error "Could not read resultset: unexpected end of stream, read 0 bytes from 4"
There is an issue communicating with the server.
Most of the time this will be caused by reading a query that has a large resultset; the server usually expects clients to read off the result set relatively quickly. The net_write_timeout server variable controls this behavior (defaults to 60s). If the client doesn't read the whole resultset in that amount of time, the server will discard the connection. If you don't expect results to be handled in this amount of time there is another possibility:
You can use the query "SET STATEMENT net_write_timeout=10000 FOR XXX" with XXX being your "normal" query. This will indicate that specifically for this query, net_write_timeout will be set to a longer time (10000 in this example).
for older servers, a specific query will have to temporarily set net_write_timeout ("SET STATEMENT net_write_timeout=..."), and set it back afterward.
if your application usually uses a lot of long queries with fetch size, the connection can be set using the "sessionVariables=net_write_timeout=xxx" option.
Connection.isValid() is a good approach. Connection.isValid() is doing a ping (ping in mysql protocol, not network ping). Connection pool using JDBC4 Validation are using automatically this Connection.isValid()
This guide will cover:
The load balancing and high availability concepts in Mariadb Connector/J for version before 3.0
The different options.
Failover and high availability were introduced in 1.2.0.
Failover occurs when a connection to a primary database server fails and the connector opens up a connection to another database server.
For example, server A has the current connection. After a failure (server crash, network down …) the connection will switch to another server (B).
Load balancing allows load (read and write) to be distributed over multiple servers.
In MariaDB (and MySQL) replication, there are 2 different replication roles:
Master role: Database server that permits read and write operations
Slave role: Database server that permits only read operations
This document describes configuration and implementation for 3 types of clusters:
Multi-Master replication cluster. All hosts have a master replication role. (example: Galera)
Master/slaves cluster: one host has the master replication role with multiple hosts in slave replication role.
Hybrid cluster: multiple hosts in master replication role with multiple hosts in slave replication role.
When initializing a connection or after a failed connection, the connector will attempt to connect to a host with a certain role (slave/master). The connection is selected randomly among the valid hosts. Thereafter, all statements will run on that database server until the connection will be closed (or fails).
The load-balancing will includes a pooling mechanism. Example: when creating a pool of 60 connections, each one will use a random host. With 3 master hosts, the pool will have about 20 connections to each host.
For a cluster composed of masters and slaves on connection initialization, there will be 2 underlying connections: one with a master host, another with a slave host. Only one connection is used at a time. For a cluster composed of master hosts only, each connection has only one underlying connection. The load will be distributed due to the random distribution of connections..
It’s the application that has to decide to use master or slave connection (the master connection is set by default). Switching the type of connection is done by using JDBC connection.setReadOnly(boolean readOnly) method. Setting read-only to true will use the slave connection, false, the master connection.
Example in standard java:
connection = DriverManager.getConnection("jdbc:mysql:replication://master1,slave1/test");
stmt = connection.createStatement();
stmt.execute("SELECT 1"); // will execute query on the underlying master1 connection
connection.setReadOnly(true);
stmt.execute("SELECT 1"); // will execute query on the underlying slave1 connection
Some frameworks render this kind of operation easier, as for example Spring @transactionnal readOnly parameter (since spring 3.0.1). In this example, setting readOnly to false will call the connection.setReadOnly(false) and therefore use the master connection.
@Autowired
private EntityManager em;
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void createContacts() {
Contact contact1 = new Contact();
contact1.setGender("M");
contact1.setName("JIM");
em.persist(contact1);
}
Generated Spring Data repository objects use the same logic: the find* method will use the slave connection, other use master connection without having to explicitly set that for each method.
On a cluster with master hosts only, the use of connection.setReadOnly(true) does not change the connection, but if the database version is 10.0.0 or higher, the session is set to readOnly if option assureReadOnly is set to true, which means that any write query will throw an exception.
When no failover/high availability parameter is set, the failover support is basic. Before executing a query, if the connection with the host is discarded, the connection will be reinitialized if parameter “autoReconnect” is set to true.
When a failover/high availability parameter is set. Check the configuration section for an overview on how to set the parameters.
There can be multiple fail causes. When a failure occurs many things will be done:
The fail host address will be put on a blacklist (shared by JVM). This host will not be used for the amount of time defined by the “loadBalanceBlacklistTimeout” parameter (default to 50 seconds). The only time a blacklisted address can be used is if all host of the same type (master/slave) are blacklisted.
The connector will check the connection (with the mysql ping protocol). If the connection is back, is not read-only, and is in a transaction, the transaction will be rollbacked (there is no way to know if the last query has been received by the server and executed).
If the failure relates to a slave connection
If the master connection is still active, the master connection will be used immediately. The query that was read-only will be relaunched and the connector will not throw any exception. A "failover" thread will be launched to attempt to reconnect a slave host. (if the query was a prepared query, this query will be re-prepared before execution)
If the master connection is not active, the driver will attempt to create a new master or slave connection with a connection loop. if any connection is found, the query will be relaunched, if not, an SQLException with sqlState like “08XXX” will be thrown.
If the failure relates to a master connection, the driver will attempt to create a new master connection with a connection loop, so the connection object will be immediately reusable.\
on failure, an SQLException with be thrown with SQLState "08XXX". If using a pool, this connection will be discarded.
on success,
if possible query will be relaunched without throwing error (if was using a slave connection, or was a SELECT query not in a transaction for example).
if not possible, an SQLException with be thrown with SQLState "25S03".
When throwing an SQLException with SQLState "08XXX", the connection will be marked as closed.
A “failover” thread will be launched to attempt to reconnect failing connection if connection is not closed.
It’s up to the application to take measures to handle SQLException. See details in application concerns.
Connection loop When initializing a connection or after a failure, the driver will launch a connection loop the only case when this connection loop will not be executed is when the failure occurred on a slave with an active master. This connection loop will try to connect to a valid host until finding a new connection or until the number of connections exceed the parameter “retriesAllDown” value (default to 120).
This loop will attempt to connect sequentially to hosts in the following order:
For a master connection :
random connect to master host not blacklisted
random connect to master blacklisted
For a slave connection :
random connect to slave host not blacklisted
random connect to master host not blacklisted (if no active master connection)
random connect to slave blacklisted
random connect to master host blacklisted (if no active master connection) The sequence stops as soon as all the underlying needed connections are found. Every time an attempt fails, the host will be blacklisted. If after an entire loop a master connection is missing, the connection will be marked as closed.
A thread pool is created in case of a master/slave cluster, the size is defined according to the number of connection. After a failure on a slave connection, readonly operations are temporary executed on the master connection. Some “failover threads” will try to reconnect the failed underlying connections. When a new slave connection is retrieved, this one will be immediately used if connection was still in read-only mode.\
An additional thread is created when setting the option "validConnectionTimeout". This thread will very that connections are all active. This is normally done by pool that call Connection.isValid().
When a failover happen a SQLException with sqlState like "08XXX" or "25S03" may be thrown.
Here are the different connection error codes:
08000
connection exception
08001
SQL client unable to establish SQL connection
08002
connection name in use
08003
connection does not exist
08004
SQL server rejected SQL connection
08006
connection failure
08007
transaction resolution unknown
25S03
invalid transaction state-transaction is rolled back
A connection pool will detect connection error in SQLException (SQLState begin with "08"), and this connection will be discarded from pool.
When a failover occurs, the connector cannot know if the last request has been received by the database server and executed. Applications may have failover design to handle these particular cases:
If the application was in autoCommit mode (not recommended), the last query may have been executed and committed. The application will have no possibility to know that but the application will be functional.
If not in autoCommit mode, the query has been launched in a transaction that will not be committed. Depending of what caused the exception, the host may have the connection open on his side during a certain amount of time. Take care of transaction isolation level that may lock too much rows.
(See About MariaDB java connector for all connection parameters) JDBC connection string format is :
jdbc:(mysql|mariadb):[replication:|sequential:|loadbalance:|aurora:]//<hostDescription>[,<hostDescription>...]/[database][?<key1>=<value1>[&<key2>=<value2>]...]
The standard option "connectTimeout" defines the socket connection timeout. By default, this option is set to 0 (no timeout).
Since there are many servers, setting this option to a small amount of time make sense. During the connection loop phase, the driver will try to connect to the server sequentially until the creation of an active connection.
Set this option to a small value (such as 2000ms - to be set according to your environment) which will permit rejecting a faulty server quickly.
Each parameter corresponds to a specific use case:
sequential
This mode supports connection failover in a multi-master environment, such as MariaDB Galera Cluster. This mode does not support load-balancing reads on slaves. The connector will try to connect to hosts in the order in which they were declared in the connection URL, so the first available host is used for all queries.For example, let's say that the connection URL is the following: jdbc:mariadb:sequential:host1,host2,host3/testdbWhen the connector tries to connect, it will always try host1 first. If that host is not available, then it will try host2. etc. When a host fails, the connector will try to reconnect to hosts in the same order.This mode has been available since MariaDB Connector/J 1.3.0
loadbalance
This mode permits load-balancing connection in a multi-master environment, such as MariaDB Galera Cluster. This mode does not support load-balancing reads on slaves. The connector performs load-balancing for all queries by randomly picking a host from the connection URL for each connection, so queries will be load-balanced as a result of the connections getting randomly distributed across all hosts.This mode has been available since MariaDB Connector/J 1.2.0
replication
This mode supports connection failover in a master-slave environment, such as a MariaDB Replication cluster. The mode supports environments with one or more masters. This mode does support load-balancing reads on slaves if the connection is set to read-only before executing the read. The connector performs load-balancing by randomly picking a slave from the connection URL to execute read queries for a connection.This mode has been available since MariaDB Connector/J 1.2.0
aurora
This mode supports connection failover in an Amazon Aurora cluster. This mode does support load-balancing reads on slave instances if the connection is set to read-only before executing the read. The connector performs load-balancing by randomly picking a slave instance to execute read queries for a connection.This mode has been available since MariaDB Connector/J 1.2.0
autoReconnect
When this parameter enabled when a Failover and Load Balancing Mode is not in use, the connector will simply try to reconnect to its host after a failure. This is referred to as Basic Failover. When this parameter enabled when a Failover and Load Balancing Mode is in use, the connector will blacklist the failed host and try to connect to a different host of the same type. This is referred to as Standard Failover. Default is false.since 1.1.7
retriesAllDown
When the connector is performing a failover and all hosts are down, this parameter defines the maximum number of connection attempts the connector will make before throwing an exception.Default: 120 seconds.since 1.2.0
failoverLoopRetries
When the connector is searching silently for a valid host, this parameter defines the maximum number of connection attempts the connector will make before throwing an exception.This parameter differs from the "retriesAllDown" parameter because this silent search is used in situations where the connector can temporarily workaround the problem, such as by using the master connection to execute reads when the slave connection fails.Default: 120.since 1.2.0
validConnectionTimeout
When multiple hosts are configured, the connector verifies that the connections haven't been lost after this much time in seconds has elapsed.When this parameter is set to 0, no verification will be done. Default:120 secondssince 1.2.0
loadBalanceBlacklistTimeout
When a connection fails, this host will be blacklisted for the amount of time defined by this parameter.When connecting to a host, the driver will try to connect to a host in the list of non-blacklisted hosts and, only if none are found, attempt blacklisted ones.This blacklist is shared inside the classloader.Default: 50 seconds.since 1.2.0
assureReadOnly
When this parameter enabled when a Failover and Load Balancing Mode is in use, and a read-only connection is made to a host, assure that this connection is in read-only mode by setting the session to read-only.Default to false.Since 1.3.0
allowMasterDownConnection
When the replication Failover and Load Balancing Mode is in use, allow the creation of connections when the master is down. If no masters are available, then the default connection will be a slave, and Connection.isReadOnly() will return true. Default: false. Since 2.2.0
Amazon Aurora is a Master/Slaves cluster composed of one master instance with a maximum of 15 slave instances. Amazon Aurora includes automatic promotion of a slave instance in case of the master instance failing. The MariaDB connector/J implementation for Aurora is specific to handle this automatic failover.
To permit development/integration on a single-node cluster, only one host can be defined. In this case, the driver behaves as for the configuration failover.
Aurora failover management steps :
Instance A is in write replication mode, instance B and C are in read replication mode.
Instance A fails.
Aurora detects A failure, and promote instance B in write mode. Instance C will change his master to use B.
Cluster end-point will change to instance B end-point.
Instance A will recover and be in read replication mode.
Every aurora instance has a specific endpoint, i.e. an URL that identify the host. Those endpoints look like xxx.yyy.zzz.rds.amazonaws.com
.
There is another endpoint named "cluster endpoint" (format xxx.cluster-yyy.zzz.rds.amazonaws.com
) which is assigned to the current master instance and will change when a new master is promoted.
In versions before 1.5.1, cluster endpoint use was discouraged, since when a failover occurs, this cluster endpoint can point for a limited time to a host that isn't the current master any more. The old recommendation was to list all specific end-points. This kind of url string will still work, but now, recommended url string has to use only cluster endpoint.
Driver will automatically discover master and slaves of this cluster from current cluster end-point during connection time. This permits adding new replicas to the cluster instance which will be discovered without changing driver configuration.
This discovery appends at connection time, so if you are using pool framework, check if this framework as a property that controls the maximum lifetime of a connection in the pool, and set a value to avoid infinite lifetime. When this lifetime is reached, pool will discard the current connection, and create a new one (if needed). New connections will use the new replicas. (If connections are never discarded, new replicas will begin to be used only when a failover occur)
The implementation is activated by specifying the “aurora” failover parameter. Recommended connection string is using cluster end-point:
jdbc:(mysql|mariadb):aurora://[clusterInstanceEndPoint[:port]]/[database][?<key1>=<value1>[&<key2>=<value2>]...]
Before driver version 1.5.1, connection string has to list all end-points:
jdbc:(mysql|mariadb):aurora://[instanceEndPoint[:port]][,instanceEndPoint[:port]...]/[database][?<key1>=<value1>[&<key2>=<value2>]...]
If setting many endpoints, the replication role of each instance must not be defined for Aurora, because the role of each instance changes over time. The driver will check the instance role after connection initialization.
Example of connection string
jdbc:mysql:aurora://cluster.cluster-xxxx.us-east-1.rds.amazonaws.com/db
Another difference is the option "socketTimeout" that defaults to 10 seconds, meaning that - if not changed - queries exceeding 10 seconds will throw exceptions.
When searching for the master instance and connecting to a slave instance, the connection order will be:
Every Aurora instance knows the hostname of the current master. If the host has been described using their instance endpoint, that will permit knowing the master instance and connecting directly to it.
If this isn’t the current master (because using IP, or possibly after a failover between step 2 and 3), the loop will connect randomly the other not blacklisted instance (minus the current slave instance).
Connect randomly to a blacklisted instance.
When searching for a slave instance, the loop connection order will be:
random not blacklisted instances (excluding the current host if connected).
random blacklisted instances . The loop will retry until the connections are found or the value of the “retriesAllDown” parameter is exceeded.
Without any query during the time defined by the validConnectionTimeout parameter (defaults to 120s) and if not set to 0, a verification will be done that the replication role of the underlying connections hasn't changed.
Aurora as a specific connection validation thread implementation. Since the role of each instance can change over time, this will validate that connections are active AND roles have not changed.
This guide will cover:
The load balancing and high availability concepts in Mariadb Connector/J.
The different options.
Failover occurs when a connection to a primary database server fails and the connector opens up a connection to another database server. For example, server A has the current connection. After a failure (server crash, network down …) the connection will switch to another server (B).
Load balancing allows load (read and write) to be distributed over multiple servers.
In MariaDB (and MySQL) replication, there are 2 different replication roles:
primary role: Database server that permits read and write operations
replica role: Database server that permits only read operations
This document describes configuration and implementation for 3 types of clusters:
Multi-primary replication cluster. All hosts have a primary role. (example: Galera)
Primary/replicas cluster: one primary host with one or multiple replicas.
Hybrid cluster: multiple primary hosts with one or multiple replicas.
When initializing a connection or after a failed connection, the connector will attempt to connect to a host with a certain role (primary/replica). The connection is selected randomly among the valid hosts. Thereafter, all statements will run on that database server until the connection will be closed (or fails).
The load-balancing includes a pooling mechanism. Example: when creating a pool of 60 connections, each one will use a random host. With 3 master hosts, the pool will have about 20 connections to each host.
For a cluster composed of primary and replicas on connection initialization, there will be 2 underlying connections: one with a primary host, another with a replica host. Only one connection is used at a time. For a cluster composed of primary hosts only, each connection has only one underlying connection. The load will be distributed due to the random distribution of connections..
It’s the application that has to decide to use primary or replica connection (the primary connection is set by default). Switching the type of connection is done by using JDBC connection.setReadOnly(boolean readOnly) method. Setting read-only to true will use the replica connection, false, the primary connection.
Example in standard java:
connection = DriverManager.getConnection("jdbc:mariadb:replication://primary1,replica1/test");
stmt = connection.createStatement();
stmt.execute("SELECT 1"); // will execute query on the underlying primary1 connection
connection.setReadOnly(true);
stmt.execute("SELECT 1"); // will execute query on the underlying replica1 connection
Some frameworks render this kind of operation easier, as for example Spring @transactionnal readOnly parameter (since spring 3.0.1). In this example, setting readOnly to false will call the connection.setReadOnly(false) and therefore use the master connection.
@Autowired
private EntityManager em;
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void createContacts() {
Contact contact1 = new Contact();
contact1.setGender("M");
contact1.setName("JIM");
em.persist(contact1);
}
Generated Spring Data repository objects use the same logic: the find* method will use the primary connection, other use primary connection without having to explicitly set that for each method.
On a cluster with primary hosts only, the use of connection.setReadOnly(false/true) won't have any impact.
When a failover/high availability parameter is set. Check the configuration section for an overview on how to set the parameters.
There can be multiple fail causes. When a failure occurs many things will be done:
connection recovery
re-execute command if possible
During failover, the fail host address will be put on a blacklist (shared by JVM) for 60 seconds.The only time a blacklisted host can be used is if all hosts of the same type (primary/replica) are blacklisted.
(connection.setReadOnly(true) was called)
If driver fails to recover connection, and connection was a replica, driver will try to connect to another replica if any and reexecute the command. If replica reconnection fails, driver will temporary use the primary connection, reexecuting the command on the primary connection, silently ignoring the error. driver won't try to reconnect to replica for 30s.
The driver will try to reconnect to any valid host (not blacklisted, or if all primary host are blacklisted trying blacklisted hosts). If reconnection fail, an SQLException with be thrown with SQLState "08XXX". If using a pool, this connection will be discarded.
on successful reconnection, there will be different cases.
If driver identify that command can be replayed without issue (for example connection.isValid(), a PREPARE/ROLLBACK command), driver will execute command without throwing any error.
Driver cannot transparently handle all cases : imagine that the failover occurs when executing an INSERT command without a transaction: driver cannot know that command has been received and executed on server. In those case, an SQLException with be thrown with SQLState "25S03".
option transactionReplay
:
Most of the time, queries occurs in transaction (ORM for example doesn't permit using auto-commit), so redo transaction implementation will solve most of failover cases transparently for user point of view.
Redo transaction approach is to save commands in transaction. When a failover occurs during a transaction, the connector can automatically reconnect and replay transaction, making failover completely transparent.
There is some limitations :
driver will buffer up to option transactionReplaySize
value (default 64) commands in a transaction
huge command will temporary disable transaction buffering for current transaction.
commands must be idempotent only (queries can be "replayable")
(See About MariaDB java connector for all connection parameters) JDBC connection string format is:
jdbc:mariadb:[replication:|sequential:|loadbalance:]//<hostDescription>[,<hostDescription>...]/[database][?<key1>=<value1>[&<key2>=<value2>]...]
The standard option "connectTimeout" defines the socket connection timeout. By default, this option is set to 30s. Since there are many servers, setting this option to a small amount of time make sense. During the reconnection phase, the driver will try to connect to the hosts sequentially until the creation of an active connection. Set this option to a small value (such as 2000ms - to be set according to your environment) which will permit rejecting a faulty server quickly.
Each parameter corresponds to a specific use case:
sequential
Description: This mode supports connection failover in a multi-master environment, such as MariaDB Galera Cluster. This mode does not support load-balancing reads on slaves. The connector will try to connect to hosts in the order in which they were declared in the connection URL, so the first available host is used for all queries.For example, let's say that the connection URL is the following: jdbc:mariadb:sequential:host1,host2,host3/testdb
When the connector tries to connect, it will always try host1 first. If that host is not available, then it will try host2. etc. When a host fails, the connector will try to reconnect to hosts in the same order.
Introduced: 1.3.0
loadbalance
Description: This mode supports connection load-balancing in a multi-master environment, such as MariaDB Galera Cluster. This mode does not support load-balancing reads on slaves. The connector performs load-balancing for all queries by randomly picking a host from the connection URL for each connection, so queries will be load-balanced as a result of the connections getting randomly distributed across all hosts. Before 2.4.2, this option was named failover
- alias still exist for compatibility -
Introduced: 1.2.0
replication
Description: This mode supports connection failover in a master-slave environment, such as a MariaDB Replication cluster. The mode supports environments with one or more masters. This mode does support load-balancing reads on slaves if the connection is set to read-only before executing the read. The connector performs load-balancing by randomly picking a slave from the connection URL to execute read queries for a connection
Introduced: 1.2.0
load-balance-read
Description: When running a multi-master cluster (i.e. Galera), writing to more than one node can lead to optimistic locking errors ("deadlocks"). Writing concurrently to multiple nodes also doesn't bring a whole lot of performance, due to having to (synchronously) replicate to all nodes anyway. This mode supports connection failover in a multi-master environment, such as MariaDB Galera Cluster. This mode does support load-balancing reads on slaves. The connector will try to connect to primary hosts in the order in which they were declared in the connection URL, so the first available host is used for all queries.For example, let's say that the connection URL is the following: jdbc:mariadb:load-balance-read:primary1,primary2,address=(host=replica1)(type=replica),address=(host=replica2)(type=replica)/DB
When the connector tries to connect, it will always try primary1 first. If that host is not available, then it will try primary2. etc. When a primary host fails, the connector will try to reconnect to hosts in the same order.For replica hosts, the connector performs load-balancing for all queries by randomly picking a replica host from the connection URL for each connection, so queries will be load-balanced as a result of the connections getting randomly distributed across all replica hosts.
Introduced: 3.5.1
aurora
Description: This mode supports connection failover in an Amazon Aurora cluster. This mode does support load-balancing reads on slave instances if the connection is set to read-only before executing the read. The connector performs load-balancing by randomly picking a slave instance to execute read queries for a connection
Introduced: 1.2.0 and not supported anymore since 3.0 version
MariaDB has supported GSSAPI authentication since MariaDB 10.1 when the gssapi authentication plugin was added.
The following subsections show how to implement GSSAPI Authentication with MariaDB Connector/J.
Support history:
version 1.4.0 : java connector support
version 1.5.0 : added native windows implementation.
The gssapi authentication plugin must be installed on the database server. The relevant user account must also be configured to use the plug-in for authentication. For example:
CREATE USER one IDENTIFIED VIA gssapi AS 'userOne@EXAMPLE.COM';
And then this user account could be used to connect to the database server with the Java connector by specifying the user name in the Java connection URL. For example:
DriverManager.getConnection("jdbc:mariadb://db.example.com:3306/db?user=one");
Since the user account is configured to use the gssapi authentication plugin on the server, the Java connector will use GSSAPI authentication when connecting.
The service principal name must be the one defined for the user account on the database server unless a different one is specified with the servicePrincipalName parameter in the connection URL.
Database server will wait for a ticket associated for the principal defined in user ('userOne@EXAMPLE'). That mean on client, user must have obtained a TGT beforehand.
As part of the security context establishment, the driver will initiate a context that will be authenticated by database. Database also be authenticated back to the driver ("mutual authentication").
Realm information are generally defined by DNS, but this can be forced using system properties. "java.security.krb5.kdc" defined the Key Distribution Center (KDC), realm by "java.security.krb5.realm". Example :
System.setProperty("java.security.krb5.kdc", "kdc1.example.com");
System.setProperty("java.security.krb5.realm", "EXAMPLE.COM");
Logging can be set using additional properties:
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("sun.security.jgss.debug", "true");
Depending on the kerberos ticket encryption, you may have to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy File. (CentOS/Red Hat Enterprise Linux 5.6 or later, Ubuntu are using AES-256 encryption by default for tickets).
On unix, you can execute the "klist -e" command to view the encryption type in use: If AES is being used, output like the following is displayed after you type the klist command (note that AES-256 is included in the output):
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: userOne@EXAMPLE
Valid starting Expires Service principal
03/30/15 13:25:04 03/31/15 13:25:04 krbtgt/EXAMPLE@EXAMPLE
Etype (skey, tkt): AES-256 CTS mode with 96-bit SHA-1 HMAC, AES-256 CTS mode with 96-bit SHA-1 HMAC
On windows GSSAPI implementation is SSPI. The java 8 native implementation as many limitations (see java ticket).
Driver contain 2 Different implementations:
a java standard implementation will use JAAS to allow java to access TGT.
a windows native implementation based on Waffle
Jaas
The driver will use the native ticket cache to get the TGT available in it using JAAS. If the System property "java.security.auth.login.config" is empty, driver will use the following configuration :
Krb5ConnectorContext {
com.sun.security.auth.module.Krb5LoginModule required
useTicketCache=true
renewTGT=true
doNotPrompt=true;
};
This permit to use current user TGT cache
limitation on windows
Main limitation are :
To permit java to retrieve TGT (Ticket-Granting-Ticket), windows host need to have a registry entry set.
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters
Value Name: AllowTGTSessionKey
Value Type: REG_DWORD
Value: 1
Kinit command must have been executed previously to connection.
Implementation is based on Waffle that support windows SSPI based on JNA.
if waffle-jna (and dependencies) is in classpath, native implementation will automatically be used. (This permit to avoid any specific problem with admin right, registry, kinit ...)
Dependencies :
"GSSException: Failure unspecified at GSS-API level (Mechanism level: No Kerberos credentials available)"
There is no active credential. Check with klist that there is an existing credential. If not create it with the "kinit" command
"java.sql.SQLInvalidAuthorizationSpecException: Could not connect: GSSAPI name mismatch, requested 'userOne@EXAMPLE.COM', actual name 'userTwo@EXEMPLE.COM'"
There is an existing credential, but doesn't correspond to the connection user. example : if user is created with a command like
CREATE USER userOne@'%' IDENTIFIED WITH gssapi AS 'userTwo@EXAMPLE.COM';
klist must show the same principal (userTwo@EXAMPLE.COM in this example)
"GSSException: No valid credentials provided (Mechanism level: Clock skew too great (37))". The Kerberos protocol requires the time of the client
and server to match: if the system clocks of the client does not match that of the KDC server, authentication will fail with this kind of error. The simplest way to synchronize the system clocks is to use a Network Time Protocol (NTP) server.
The recommended way to install MariaDB Connector/J is to use a package manager like Maven or Gradle.
To install MariaDB Connector/J with Maven, add the following dependency to your pom.xml
configuration file:
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>$VERSION</version>
</dependency>
Be sure to replace $VERSION
with a valid MariaDB Connector/J version number. See About MariaDB Connector/J: Java Compatibility to determine which MariaDB Connector/J release series supports your Java version.
To install MariaDB Connector/J with Gradle, add the following dependency to your build.gradle
configuration file:
implementation 'org.mariadb.jdbc:mariadb-java-client:$VERSION'
Be sure to replace $VERSION
with a valid MariaDB Connector/J version number. See About MariaDB Connector/J: Java Compatibility to determine which MariaDB Connector/J release series supports your Java version.
It is not generally the recommended method, but MariaDB Connector/J can also be installed by manually installing the .jar
file to a directory in your CLASSPATH.
MariaDB Connector/J .jar
files can be downloaded from the following URL:
This section deals with building the connector from source and testing it. If you have downloaded a ready-built connector, in a jar file, then this section may be skipped.
The source code is available at the mariadb-connector-j repository on GitHub. You can clone it by executing the following:
git clone https://github.com/MariaDB/mariadb-connector-j.git
If you would prefer a packages source tarball release, then MariaDB Connector/J .jar
source code tarballs can be downloaded from the following URL:
MariaDB Connector/J has the following build requirements:
Java JDK
If you would like to run the unit tests, then you'll need a MariaDB or MySQL server. It has to meet the following requirements:
It must be listening on localhost
on TCP port 3306
.
It must have a database called testj
.
It must have a root
user account with an empty password.
If you would like to build MariaDB Connector/J and run the unit tests, then execute the following:
mvn package
If you would like to build MariaDB Connector/J without running the unit tests, then execute the following:
mvn -Dmaven.test.skip=true package
Once the build is complete, you should have a .jar
file with a name like mariadb-java-client-x.y.z.jar
in the target
subdirectory.
MariaDB Connector/J is used to connect applications developed in Java to MariaDB and MySQL databases using the standard JDBC API.
A MariaDB / MySQL server running on localhost using the default port 3306
Java version >= 8
Gradle
Create a simple Java project with gradle :
gradle init --type java-library
The new project will be created in current folder.
This folder contains the file build.gradle
that permits configuring Gradle.
Declares driver in build.gradle
(and setting java minimal version to 1.8) :
The build.gradle
file will then be :
// Apply the java-library plugin to add support for Java Library
apply plugin: 'java-library'
// In this section you declare where to find the dependencies of your project
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'
// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:22.0'
// Use JUnit test framework
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
implementation 'org.mariadb.jdbc:mariadb-java-client:3.4.1'
}
Standard JDBC methods DriverManager.getConnection(String url, String user, String password) are used to connect to the database.
Basic url string is standardized for the MariaDB driver: jdbc:(mysql|mariadb):[replication:|failover:|sequential:|aurora:]//<hostDescription>[,<hostDescription>...]/[database][?<key1>=<value1>[&<key2>=<value2>]]
The MariaDB driver is registered automatically for a url that begins with "jdbc:mariadb:" or "jdbc:mysql:".
Assuming a server is installed on the local machine with default port 3306, the url String is then "jdbc:mariadb://localhost/"
.
Create a new file App.java
in src/main/java
with the following content: (assuming a server is installed on the local machine, with a user "root" with no password) :
import java.sql.*;
public class App {
public static void main( String[] args ) throws SQLException {
//create connection for a server installed in localhost, with a user "root" with no password
try (Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost/", "root", null)) {
// create a Statement
try (Statement stmt = conn.createStatement()) {
//execute query
try (ResultSet rs = stmt.executeQuery("SELECT 'Hello World!'")) {
//position result to first
rs.first();
System.out.println(rs.getString(1)); //result is "Hello World!"
}
}
}
}
}
To run class App, add a new task in build.gradle:
task run (type: JavaExec){
description = "get started run"
main = 'App'
classpath = sourceSets.main.runtimeClasspath
}
build project:
c:\temp\gradle>gradle build
BUILD SUCCESSFUL in 1s
4 actionable tasks: 4 up-to-date
Gradle will automatically download the driver and compile the App file.
To run the App class, just launch the previously-defined task "run":
c:\temp\gradle>gradle run
> Task :run
Hello World!
BUILD SUCCESSFUL in 1s
2 actionable tasks: 1 executed, 1 up-to-date
More information at About MariaDB Connector/J
MariaDB Connector/J is used to connect applications developed in Java to MariaDB and MySQL databases using the standard JDBC API.
A MariaDB / MySQL server running on localhost using the default port 3306
Java version >= 8
Maven
Create a simple Java project with Maven:
mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Replace "com.mycompany.app" and "my-app" with appropriate values
The new project will be created in the folder "my-app". This folder contains the file pom.xml
that permits configuring Maven.
Declares driver in pom.xml
(and setting java minimal version to 1.8) :
pom.file will then be :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>my-app</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Standard JDBC methods DriverManager.getConnection(String url, String user, String password) are used to connect to the database.
Basic url string is standardized for the MariaDB driver : jdbc:(mysql|mariadb):[replication:|failover:|sequential:|aurora:]//<hostDescription>[,<hostDescription>...]/[database][?<key1>=<value1>[&<key2>=<value2>]]
The MariaDB driver is registered automatically for a url that begins with "jdbc:mariadb:" or "jdbc:mysql:".
Assuming a server is installed on the local machine with default port 3306, the url String is then "jdbc:mariadb://localhost/"
.
Basic maven archetype has created a simple Java file App.java
in src/main/java/com/mycompany/app
.
Update the file App.java
with the following content: (assuming a server is installed on the local machine, with a user "root" with no password) :
package com.mycompany.app;
import java.sql.*;
public class App {
public static void main( String[] args ) throws SQLException {
//create connection for a server installed in localhost, with a user "root" with no password
try (Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost/", "root", null)) {
// create a Statement
try (Statement stmt = conn.createStatement()) {
//execute query
try (ResultSet rs = stmt.executeQuery("SELECT 'Hello World!'")) {
//position result to first
rs.first();
System.out.println(rs.getString(1)); //result is "Hello World!"
}
}
}
}
}
Compile project:
mvn install
Maven will automatically download the driver and compile the App file.
Run it using maven:
C:\temp\my-app>mvn exec:java -Dexec.mainClass="com.mycompany.app.App"
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building my-app 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.6.0:java (default-cli) @ my-app ---
Hello World!
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.837 s
[INFO] Finished at: 2017-10-25T11:16:06+02:00
[INFO] Final Memory: 10M/245M
[INFO] ------------------------------------------------------------------------
More information at About MariaDB Connector/J
MariaDB Connector/J is used to connect applications developed in Java to MariaDB and MySQL databases using the standard JDBC API. The library is LGPL licensed.
<< back to About MariaDB Connector/J
29 Nov 2012
1.0.0
Stable (GA)
Java 6
Since 1.5.0, the "useBatchMultiSend" option permits sending queries by batch. If disabled, queries are sent one by one, waiting for the result before sending thenext one. If enabled, queries will be sent by batch corresponding to the value of the useBatchMultiSendNumber option (default 100). Results will be read after a while, avoiding a lot of network latency when the client and the server aren't on the same host. This option is only used for JDBC executeBatch(). This option is particularly efficient when the client is distant from the server.
Here is a benchmark using a client and server on 2 different hosts (ping of 0.350ms between 2 hosts):
By default, the driver communicates with the server following a request–response messaging pattern:
As soon as the driver sends data, the driver will block until data is available from the input socket.
JDBC permit batching. Example :
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO test(data1, data2) VALUES (?, ?)");
for (int i = 0; i < 3; i++) {
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "value" + i);
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
When the "useBatchMultiSend" option is disabled, batches like this will send data one by one following the traditional request-response messaging pattern. Here is an example using a prepare query ("useServerPrepStmts" is enabled) :
Same example with "useBatchMultiSend" enabled. Requests are sent by bulk, saving network latency:
Advantages :
a lot more efficient.
Inconvenient:
if an error occurs, and "continueBatchOnError" is disabled (default enable), some other data may have been already sent and executed.
Bulk split
All data is not sent at once, but by batch corresponding to the useBatchMultiSendNumber value. Reads begin asynchronously after the first send command. The driver will then wait until it has read all results corresponding to the sent data before sending new data.
MariaDB Connector/J provides 2 different Datasource pool implementations:
MariaDbDataSource
: The basic implementation. It creates a new connection each time the getConnection()
method is called.
MariaDbPoolDataSource
: A connection pool implementation. It maintains a pool of connections, and when a new connection is requested, one is borrowed from the pool.
When using MariaDbPoolDataSource, different options permit specifying the pool behaviour:
pool
Use pool. This option is useful only if not using a DataSource object, but only a connection object. Default: false. since 2.2.0
poolName
Pool name that permits identifying threads.default: auto-generated as MariaDb-pool-since 2.2.0
maxPoolSize
The maximum number of physical connections that the pool should contain. Default: 8. since 2.2.0
minPoolSize
When connections are removed due to not being used for longer than "maxIdleTime", connections are closed and removed from the pool. "minPoolSize" indicates the number of physical connections the pool should keep available at all times. Should be less or equal to maxPoolSize.Default: maxPoolSize value. Since 2.2.0
poolValidMinDelay
When asking a connection to pool, the pool will validate the connection state. "poolValidMinDelay" permits disabling this validation if the connection has been borrowed recently avoiding useless verifications in case of frequent reuse of connections. 0 means validation is done each time the connection is asked.Default: 1000 (in milliseconds). Since 2.2.0
maxIdleTime
The maximum amount of time in seconds that a connection can stay in the pool when not used. This value must always be below @wait_timeout value - 45s Default: 600 in seconds (=10 minutes), minimum value is 60 seconds. Since 2.2.0
staticGlobal
Indicates the values of the global variables max_allowed_packet, wait_timeout, autocommit, auto_increment_increment, time_zone, system_time_zone and tx_isolation) won't be changed, permitting the pool to create new connections faster.Default: false. Since 2.2.0
useResetConnection
When a connection is closed() (given back to pool), the pool resets the connection state. Setting this option, the prepare command will be deleted, session variables changed will be reset, and user variables will be destroyed when the server permits it (>= MariaDB 10.2.4, >= MySQL 5.7.3), permitting saving memory on the server if the application make extensive use of variables. Must not be used with the useServerPrepStmts optionDefault: false. Since 2.2.0
registerJmxPool
Register JMX monitoring pools.Default: true. Since 2.2.0
Example of use:
MariaDbPoolDataSource pool = new MariaDbPoolDataSource("jdbc:mariadb://server/db?user=myUser&maxPoolSize=10");
try (Connection connection = pool.getConnection()) {
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT CONNECTION_ID()");
rs.next();
System.out.println(rs.getLong(1)); //4489
}
}
try (Connection connection = pool.getConnection()) {
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT CONNECTION_ID()");
rs.next();
System.out.println(rs.getLong(1)); //4489 (reused same connection)
}
}
pool.close();
Pooling can be configured at connection level using the "pool" option: (The main difference is that there is no accessible object to close the pool if needed.)
//option "pool" must be set to indicate that pool has to be used
String connectionString = "jdbc:mariadb://server/db?user=myUser&maxPoolSize=10&pool";
try (Connection connection = DriverManager.getConnection(connectionString)) {
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT CONNECTION_ID()");
rs.next();
System.out.println(rs.getLong(1)); //4506
}
}
try (Connection connection = DriverManager.getConnection(connectionString)) {
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT CONNECTION_ID()");
rs.next();
System.out.println(rs.getLong(1)); //4506 (reused same connection)
}
}
Each time a connection is asked, if the pool contains a connection that is not used, the pool will validate the connection, exchanging an empty MySQL packet with the server to ensure the connection state, then give the connection. The pool reuses connection intensively, so this validation is done only if a connection has not been used for a period (specified by the "poolValidMinDelay" option with the default value of 1000ms).
If no connection is available, the request for a connection will be put in a queue until connection timeout. When a connection is available (new creation or released to the pool), it will be use to satisfy queued requests in FIFO order.
A dedicated thread will handle new connection creation (one by one) to avoid a connection burst. This thread will create connections until "maxPoolSize" if needed with a minimum connection of "minPoolSize".
99.99% of the time, a connection is created, a few queries are executed, then the connection is released. Creating connections one after another permits handling sudden peaks of connection, avoiding creating lot of connections immediately and dropping them after idle timeout:
On connection.close(), a connection is not really closed, but given back to the pool. The pool will then reset the connection state. The reset goal is that the next connection received from the pool has the same state as a new freshly created connection.
Reset operations:
Rollback remaining active transactions
Reuse the initial configured database if changed
Default connection read-only state to false (master in a masters/slaves configuration) if changed
Re-initialize socket timeout if changed
autocommit reset to default
Transaction Isolation if changed
If the server version is >= MariaDB 10.2.4 (5.7.3 for MySQL server), then the "useResetConnection" option can be used. This option will delete all user variables, and reset session variables to their initial state.
An additional thread will periodically close idle connections not used for a time corresponding to option "maxIdleTime". The pool will ensure recreating the connection to satisfy the "minPoolSize" option value.
This avoids keeping unused connections in the pool, overloading the server uselessly. If the "staticGlobal" option is set, the driver will ensure that the "maxIdleTime" option is less than the server wait_timeout setting.
When creating a connection, driver need to execute between 2 to 4 additional queries after socket initialization / ssl initialization depending on options.
If your application never change the following global variables don't change (rarely changed) :
Then you can use the option "staticGlobal". Those value will be kept in memory, avoiding any additional queries when establishing a new connection (connection creation can be 30% faster, depending on network)
Additional enhancement then : Statement.cancel, Connection.abort() methods using pool are super fast, because of reusing a connection from pool.
If any change occur, JMX method resetStaticGlobal permit to reset values from memory.
if not disabled by option "registerJmxPool", JMX give some information on pool state. MBeans name are like "org.mariadb.jdbc.pool:type=*".
Some statistics of current pool :
long getActiveConnections(); -> indicate current used connection
long getTotalConnections(); -> indicate current number of connections in pool
long getIdleConnections(); -> indicate the number of connection currently not used
long getConnectionRequests(); -> indicate threads number that wait for a connection.
Example accessing JMX through java :
try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "jdbc:mariadb://localhost/testj?user=root&maxPoolSize=5&minPoolSize=3&poolName=PoolTestJmx")) {
try (Connection connection = pool.getConnection()) {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=PoolTest*");
Set<ObjectName> objectNames = server.queryNames(filter, null);
ObjectName name = objectNames.iterator().next();
System.out.println(server.getAttribute(name, "ActiveConnections")); //1
System.out.println(server.getAttribute(name, "TotalConnections")); //3
System.out.println(server.getAttribute(name, "IdleConnections")); //2
System.out.println(server.getAttribute(name, "ConnectionRequests")); //0
}
}
This document explains how to configure the MariaDB Java driver to support TLS/SSL.
Data can be encrypted during transfer using the Transport Layer Security (TLS) protocol. TLS/SSL permits transfer encryption, and optionally server and client identity validation.
To ensure that SSL is correctly configured on the server, the query "SELECT @@have_ssl;" must return YES. If not, please refer to the server documentation.
Connecting to a server that doesn't support TLS with TLS option set, an exception "Trying to connect with ssl, but ssl not enabled in the server" will be thrown.
The MariaDB Java driver by default uses java default supported protocols . If the servers are MariaDB on Unix or version >= 10.2 , consider adding TLSv1.2 protocol. This can be set using the "enabledSslProtocolSuites" option (example: enabledSslProtocolSuites=TLSv1.2,TLSv1.3).
In addition to the protocol, the driver relies on the Java default cipher list. The Java default enabled ciphers are listed here. JAVA allows cipher suites to be removed/excluded from use in the security policy using the Java system property "jdk.tls.disabledAlgorithms". The specific list of ciphers to be used can be set using the "enabledSslCipherSuites" driver option (example : "enabledSSLCipherSuites=TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,...")
By default, the driver can be configured to use TLS, even if the user used for authentication is not set to use TLS, but the recommendation is to use a user created with "REQUIRE SSL". See CREATE USER for more details, to ensure connector use TLS.
Example;
CREATE USER 'myUser'@'%' IDENTIFIED BY 'MyPwd';
GRANT ALL ON db_name.* TO 'myUser'@'%' REQUIRE SSL;
Since version 3 of the connector, TLS is enable client side setting option "sslMode". The following values are supported:
disable: Do not use SSL/TLS (default)
trust: Only use SSL/TLS for encryption. Do not perform certificate or hostname verification.
verify-ca: Use SSL/TLS for encryption and perform certificates verification, but do not perform hostname verification.
verify-full: Use SSL/TLS for encryption, certificate verification, and hostname verification. This is the standard TLS behavior. Alias "true"/"1" are possible like "sslMode=true"
To ensure TLS is enable server side, first try with option "sslMode=trust".
try (Connection con = DriverManager.getConnection("jdbc:mariadb://localhost/myDb?user=myUser&password=MyPwd"
+ "&sslMode=trust")) {
try (Statement stmt = con.createStatement()) {
stmt.execute("select 1");
}
}
Please note that this is not safe for production use, since even if all exchanges will be encrypted, the identity of the server is not verified, permitting man in the middle fake servers.
To validate the server identity, server root certificates and intermediate certificates must be trusted client side.
There are several ways to achieve this:
Java has a default truststore that contains well-known CAs including Let's Encrypt (since java 8u101), VeriSign, Entrust, and GTE CyberTrust.trusted Certificate Authorities (CA). If the server certificate is signed using a certificate chain using a root CA known in java default truststore, nothing has to be configured client side. The location of default truststore is set in system property "javax.net.ssl.trustStore".
provide the certificate using option "serverSslCert".
Zero-configuration TLS encyption using 3.4+ version of the connector and MariaDB 11.4+ server. See dedicated chapter.
By default when sslMode is set (not disabled), connector will use "serverSslCert" is set or the default truststore if not. Using default truststore can be disable setting option "fallbackToSystemTrustStore" to false.
Java trustStore is a file that contains certificates of trusted SSL servers, or of Certificate Authorities trusted to identify servers. Truststore can be protected by a password.
The Java search order for locating the trust store is:
system property "javax.net.ssl.trustStore"
$JAVA_HOME/lib/security/jssecacerts
$JAVA_HOME/lib/security/cacerts (shipped by default)
To add a certificate from a CA not included in the truststore, locate the default truststore on your system. The default truststore is located in the $JAVA_HOME/jre/lib/security/cacerts.
//copy the java truststore to jssecacerts
cp $JAVA_HOME/jre/lib/security/cacerts $JAVA_HOME/jre/lib/security/jssecacerts
//add your certificat to truststore
keytool -importcert -file myCA-root.cer -alias myCA -keystore /usr/java/default/jre/lib/security/jssecacerts -storepass changeit
with our previous example, change sslMode to "verify-full":
try (Connection con = DriverManager.getConnection("jdbc:mariadb://localhost/myDb?user=myUser&password=MyPwd"
+ "&sslMode=verify-full")) {
try (Statement stmt = con.createStatement()) {
stmt.execute("select 1");
}
}
The "serverSslCert" option permits setting the certificate location. The location can be used in one of 3 forms:
serverSslCert=/path/to/cert.pem (full path to certificate)
serverSslCert=classpath:relative/cert.pem (relative to current classpath)
or as verbatim DER-encoded certificate string "------BEGING CERTIFICATE-----..." .
Example :
try (Connection con = DriverManager.getConnection("jdbc:mariadb://localhost/myDb?user=myUser&password=MyPwd&serverSslCert=/path/to/cert.pem&&sslMode=verify-full")) {
try (Statement stmt = con.createStatement()) {
stmt.execute("select 1");
}
}
TLS use has been simplified with MariaDB Server 11.4. For MariaDB Connector/J 3.4+ to establish an SSL encrypted connection to MariaDB Server 11.4, enabling SSL does not require any special configuration apart from using "sslMode=verify-full"
During TLS exchange, server will send certificate, client will validate server identity with the certificate fingerprint and password hashing. This required that the password is not empty.
Mutual SSL authentication or certificate based mutual authentication refers to two parties authenticating each other through verifying the provided digital certificate so that both parties are assured of the others' identity.
To enable mutual authentication, the user must be created with "REQUIRE X509" so the server asks the driver for client certificates. See CREATE USER for more details.
Example:
CREATE USER 'myUser'@'%' IDENTIFIED BY 'MyPwd';
GRANT ALL ON db_name.* TO 'myUser'@'%' REQUIRE X509;
If the user is not set with REQUIRE X509, only one way authentication will be done
The client (driver) must then have its own certificate too (and related private key). If the driver doesn't provide a certificate, and the user used to connect is defined with "REQUIRE X509", the server will then return a basic "Access denied for user".
Java stores this client certificate and private key in a keyStore file. A keystore file is similar to trustore, in fact trustore and keystore are often the same file.
Example of generating a keystore in JKS format :
# generate a keystore with the client cert & key
openssl pkcs12 \
-export \
-in "${clientCertFile}" \
-inkey "${clientKeyFile}" \
-out "${tmpKeystoreFile}" \
-name "mariadbAlias" \
-passout pass:kspass
# convert PKSC12 to JKS
keytool \
-importkeystore \
-deststorepass kspass \
-destkeypass kspass \
-destkeystore "${clientKeystoreFile}" \
-srckeystore ${tmpKeystoreFile} \
-srcstoretype PKCS12 \
-srcstorepass kspass \
-alias "mariadbAlias"
Like truststore, the Java default keystore can be used, then no additional option is needed, or a dedicated keystore by using the "keyStore" option to indicate location and the "keyStorePassword" option to indicate the keystore password. In JKS keystore, an additional password for a specific key may have been set. The "keyPassword" option permits setting this password.
If the following error occurs: "java.sql.SQLException: Trying to connect with ssl, but ssl not enabled in the server", SSL is not enabled on the server-side. Since the "useSSL=true" option is set, the connection failed. Execute "show variables like '%ssl%';" on the server-side to identify the SSL issue.
When the driver tries to connect using SSL, but no certificate is provided, or the "trustServerCertificate=true" option is not set, the driver will fail with the following exception "Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"
Solution:
not recommended: set the "sslMode" option to "trust" value
add the server certificate to the driver (see documentation above).
This can occur for a number of reasons:
The user / password is incorrect.
Some SSL options have been set on the user (can be checked using "select SSL_TYPE, SSL_CIPHER, X509_ISSUER, X509_SUBJECT FROM mysql.user u where u.User = '';) and the connection attempt doesn't meet those requirements.