The most recent release of MariaDB Connector/J is:
MariaDB Connector/J 1.2.0

DateReleaseStatusRelease NotesChangelog
17 Jul 2015MariaDB Connector/J 1.2.0Stable (GA)Release NotesChangelog
18 Jun 2015MariaDB Connector/J 1.1.9Stable (GA)Release NotesChangelog
16 Jan 2015MariaDB Java Client 1.1.8Stable (GA)Release NotesChangelog
2 Apr 2014MariaDB Java Client 1.1.7Stable (GA)Release NotesChangelog
18 Feb 2014MariaDB Java Client 1.1.6Stable (GA)Release NotesChangelog
18 Sep 2013MariaDB Java Client 1.1.5Stable (GA)Release NotesChangelog
10 Sep 2013MariaDB Java Client 1.1.4Stable (GA)Release NotesChangelog
1 Jul 2013MariaDB Java Client 1.1.3Stable (GA)Release NotesChangelog
2 May 2013MariaDB Java Client 1.1.2Stable (GA)Release NotesChangelog
1 Mar 2013MariaDB Java Client 1.1.1Stable (GA)Release NotesChangelog
15 Jan 2013MariaDB Java Client 1.1.0Stable (GA)Release NotesChangelog
29 Nov 2012MariaDB Java Client 1.0.0Stable (GA)

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.

Introduction

MariaDB Connector/J is a Type 4 JDBC driver. It was developed specifically as a lightweight JDBC connector for use with MySQL and MariaDB database servers. It's originally based on the Drizzle JDBC code, and with a lot of additions and bug fixes.

Obtaining the driver

The driver source code can be downloaded from: https://downloads.mariadb.org/connector-java/

Pre-built .jar files can be downloaded from: https://code.mariadb.com/connectors/java/

Installing the driver

Installation of the client library is very simple, the jar file should be saved in an appropriate place for your application and the classpath of your application altered to include MariaDB Connector/J rather than your current connector.

Using maven :

<dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>xxx</version>
</dependency>

Requirements

  • Java 7 (until April 2015) or 8
  • com.sun.JNA is used by some library functions and a jar is available at https://github.com/twall/jna
    • only needed when connecting to the server with unix sockets or windows shared memory
  • A MariaDB or MySQL Server
  • maven (only if you want build from source)

Source code

The source code is available on GitHub: https://github.com/MariaDB/mariadb-connector-j and the most recent development version can be obtained using the following command:

git clone https://github.com/MariaDB/mariadb-connector-j.git

License

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.

Building and testing the driver

The 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.

MariaDB Client Library for Java Applications uses maven for build. You first need to ensure you have both java and maven installed on your server before you can build the driver.

To run the unit test, you'll need a MariaDB or MySQL server running on localhost (on default TCP port 3306) and a database called 'test', and user 'root' with empty password

git clone https://github.com/MariaDB/mariadb-connector-j.git #  Or, unpack the source distribution tarball
cd mariadb-connector-j
# For the unit test run, start local mysqld mysqld, 
# ensure that user root with empty password can login
mvn package
# If you want to build without running unit  tests, use
# mvn -Dmaven.test.skip=true package

After that, you should have JDBC jar mariadb-java-client-x.y.z.jar in the 'target' subdirectory

Using the driver

The following subsections show the formatting of JDBC connection strings for MariaDB, MySQL database servers. Additionally, sample code is provided that demonstrates how to connect to one of these servers and create a table.

Driver Manager

Applications designed to use the driver manager to locate the entry point need no further configuration, MariaDB Connector/J will automatically be loaded and used in the way any previous MySQL driver would have been.

Driver Class

Please note that the driver class provided by MariaDB Connector/J is not com.mysql.jdbc.Driver but org.mariadb.jdbc.Driver!

Connection strings

Format of the JDBC connection string is

jdbc:(mysql|mariadb):[replication:|failover:]//<hostDescription>[,<hostDescription>...]/[database][?<key1>=<value1>[&<key2>=<value2>]]

HostDescription:

<host>[:<portnumber>]  or address=(host=<host>)[(port=<portnumber>)][(type=(master|slave))]

Host must be a DNS name or IP address. In case of ipv6 and simple host description, the IP address must be written inside brackets. The default port is 3306. The default type is master. If replication failover is set, by default the first host is master, and the others are slaves.

Examples :

  • localhost:3306
  • [2001:0660:7401:0200:0000:0000:0edf:bdd7]:3306
  • somehost.com:3306
  • address=(host=localhost)(port=3306)(type=master)

Failover parameters

Failover was introduced in Connector/J 1.2.0.

replicationFailover support for master-slave replication with a random pick strategy.
failoverFailover support for master-master with a random balance strategy (for galera for example).

Optional URL parameters

General remark: Unknown options accepted and are silently ignored.

Following options are currently supported.

userDatabase user name.
since 1.0.0
passwordPassword of database user.
since 1.0.0
useFractionalSecondsCorrectly 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
allowMultiQueriesAllows multiple statements in single executeQuery.
example:
insert into ab (i) values (1); insert into ab (i) values (2);
will be rewritten
insert into ab (i) values (1), (2);
Default: false.
since 1.0.0
dumpQueriesOnExceptionIf set to 'true', exception thrown during query execution contain query string.
Default: false.
since 1.1.0
useCompressionallow compression in MySQL Protocol.
Default: false.
since 1.0.0
useSSLForce SSL on connection.
Default: false.
since 1.1.0
trustServerCertificateWhen using SSL, do not check server's certificate.
Default: false.
since 1.1.1
serverSslCertServer's certificatem in DER form, or server's CA certificate.
Can be used in one of 3 forms :
* sslServerCert=/path/to/cert.pem (full path to certificate)
* sslServerCert=classpath:relative/cert.pem (relative to current classpath)
* or as verbatim DER-encoded certificate string "------BEGING CERTIFICATE-----" .
since 1.1.3
socketFactoryto use custom socket factory, set it to full name of the class that implements javax.net.SocketFactory.
since 1.0.0
tcpNoDelaySets corresponding option on the connection socket.
since 1.0.0
tcpKeepAliveSets corresponding option on the connection socket.
since 1.0.0
tcpAbortiveCloseSets corresponding option on the connection socket.
since 1.1.1
tcpRcvBufset buffer size for TCP buffer (SO_RCVBUF).
since 1.0.0
tcpSndBufset buffer size for TCP buffer (SO_SNDBUF).
since 1.0.0
pipeOn Windows, specify named pipe name to connect to mysqld.exe.
since 1.1.3
tinyInt1isBitDatatype mapping flag, handle MySQL Tiny as BIT(boolean).
Default: true.
since 1.0.0
yearIsDateTypeYear is date type, rather than numerical.
Default: true.
since 1.0.0
sessionVariables<var>=<value> pairs separated by comma, mysql session variables, set upon establishing successfull connection.
since 1.1.0
localSocketAllows to connect to database via Unix domain socket, if server allows it.
The value is the path of Unix domain socket (i.e "socket" database parameter : select @@socket) .
since 1.1.4
sharedMemoryAllowed to connect database via shared memory, if server allows it.
The value is base name of the shared memory.
since 1.1.4
localSocketAddressHostname or IP address to bind the connection socket to a local (UNIX domain) socket.
since 1.1.7
socketTimeoutDefined the network socket timeout (SO_TIMEOUT) in milliseconds.
Default: 0 milliseconds(0 disable this timeout).
since 1.1.7
interactiveClientSession timeout is defined by the wait_timeout server variable. Setting interactiveClient to true will tell server to use the interactive_timeout server variable.
Default: false.
since 1.1.7
useOldAliasMetadataBehaviorMetadata ResultSetMetaData.getTableName() return the physical table name. "useOldAliasMetadataBehavior" permit to activate the legacy code that send the table alias if set.
Default: false.
since 1.1.9
createDatabaseIfNotExistthe specified database in url will be created if nonexistent.
Default: false.
since 1.1.7
serverTimezoneDefined the server time zone.
to use only if jre server as a different time implementation of the server.
(best to have the same server time zone when possible).
since 1.1.7
rewriteBatchedStatementsrewrite batchedStatement to have only one server call.
Default: false.
since 1.1.8

Failover/High availability URL parameters

autoReconnectDriver must recreateConnection after a failover
Default to false.
since 1.1.7
failOnReadOnlyAfter a failover on a master host and no other master found, indicate if connection must fall on a read-only host temporary.
Default: false.
since1.2.0
secondsBeforeRetryMasteronly when "failOnReadOnly" is enabled.
Number of seconds to issue before falling back to master when failed over (when using multi-host failover).
Whichever condition is met first, 'queriesBeforeRetryMaster' or 'secondsBeforeRetryMaster' will cause an attempt to be made to reconnect to the master.
Default:50 seconds.
since 1.2.0
queriesBeforeRetryMasteronly when "failOnReadOnly" is enabled.
Number of queries to issue before falling back to master.
Whichever condition is met first, 'queriesBeforeRetryMaster' or 'secondsBeforeRetryMaster' will cause an attempt to be made to reconnect to the master.
Default: 30 queries.
since 1.2.0
retriesAllDownWhen searching a valid host, max number of connection attempts before throwing an exception.
Default: 120 seconds.
since 1.2.0
failoverLoopRetriesWhen searching silently a valid host, max number of connection attempts.
this differ from "retriesAllDown" parameter, because this silent search is for exemple used after a disconnection of a slave connection when using the master connection
Default: 120.
since 1.2.0
validConnectionTimeoutWhen in multiple hosts, after this time in second without used, verification that the connections an't lost.
When 0, no verification will be done.
Default:120 seconds
since 1.2.0
loadBalanceBlacklistTimeoutWhen a connection failed, this host will be blacklisted during the "loadBalanceBlacklistTimeout" amount of time.
When connecting a host, the driver will try to connect in the list of hosts not blacklisted and after that only on blacklisted one if none has been found.
this blacklist is shared inside a same classloader
default: 50 seconds.
since 1.2.0

JDBC API Implementation Notes

Streaming result sets

By default, Statement.executeQuery() will read full result set from server before returning. With large result sets, this will require large amounts of memory. Better behavior in this case would be reading row-by-row, with ResultSet.next(), so called "streaming" feature. It is activated using Statement.setFetchSize(Integer.MIN_VALUE)

Prepared statements

The driver only uses text protocol to communicate with the database. Prepared statements (parameter substitution) is handled by the driver, on the client side.

CallableStatement

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 the mysql.proc table.

Optional JDBC classes

Following optional interfaces are implemented by the org.mariadb.jdbc.MySQLDataSource class : javax.sql.DataSource, javax.sql.ConnectionPoolDataSource, javax.sql.XADataSource

Usage examples

The following code provides a basic example of how to connect to a MariaDB or MySQL server and create a table.

Creating a table on a MariaDB or MySQL Server

Connection  connection = DriverManager.getConnection("jdbc:mysql://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();

Comments

Comments loading...