Connect with MariaDB Connector/J

Java developers can use MariaDB Connector/J to establish client connections with MariaDB Enterprise.

Connection URL Syntax

The connection URL syntax used to connect to MariaDB with Connector/J is as follows. Optional parameters are shown enclosed in []:

jdbc:mariadb:[<haMode>:]//[<hostDescription>[,<hostDescription>]]/[<database>][?<key1>=<value1>[&<key2>=<value2>]] }

The connection URL:

Example Connection URLs

Some example connection URLs:

jdbc:mariadb://192.0.2.1/

jdbc:mariadb://192.0.2.1/?user=db_user&password=db_user_password

jdbc:mariadb://192.0.2.1/database?user=db_user&password=db_user_password

jdbc:mariadb://192.0.2.1:3307/database?user=db_user&password=db_user_password

jdbc:mariadb://mariadb.example.com/database?user=db_user&password=db_user_password

jdbc:mariadb://mariadb.example.com:3307/database?user=db_user&password=db_user_password

jdbc:mariadb://localhost/database?localSocket=/var/lib/mysql/mysql.sock&user=db_user&password=db_user_password

High Availability (HA) Modes

MariaDB Connector/J supports the use of multiple nodes in JDBC connection URL. For multi-node environments, Connector/J provides basic failover between the nodes when establishing connections.

Connector/J also features optional High Availability (HA) modes, which provide additional support for load balancing and failover.

HA modes are useful in multi-node environments, such as:

HA Mode

Description

failover

Alias of the loadbalance HA mode.

loadbalance

Balances read and write load between configured nodes.

replication

Balances read and write load between configured primary servers. Balances read load between configured replica servers.

sequential

Provides connection failover between configured nodes.

Load Balancing Mode

In the loadbalance HA mode, MariaDB Connector/J load balances JDBC connections across multiple MariaDB Enterprise Server nodes or MariaDB Community Server nodes, as specified in the JDBC connection string. When sending read and write queries, Connector/J balances the load by randomly selecting from configured nodes. This HA mode does not support load balancing read queries across replica servers.

To enable the loadbalance HA mode:

jdbc:mariadb:loadbalance://192.0.2.1,192.0.2.2,192.0.2.3/test

The failover HA mode is an alias of the loadbalance mode.

Replication Mode

In the replication HA mode, MariaDB Connector/J load balances JDBC connections across multiple MariaDB Enterprise Server nodes or MariaDB Community Server nodes, as specified in the JDBC connection string. When sending read and write queries, Connector/J balances the load between available primary servers. It can also balance the read query load across available replica servers.

To enable the replication HA mode:

jdbc:mariadb:replication://192.0.2.1,192.0.2.2,192.0.2.3/test

Sequential Mode

In the sequential HA mode, MariaDB Connector/J provides failover for JDBC connections across multiple MariaDB Enterprise Server nodes or MariaDB Community Server nodes, as specified in the JDBC connection string. Connector/J selects the first node from the configured sequence. If the connection attempt fails, it attempts to connect to the next node in the sequence.

To use the Sequential HA mode:

jdbc:mariadb:sequential://192.0.2.1,192.0.2.2,192.0.2.3/test

Host Description

The hostDescription field in the connection URL has a simple syntax and a complex syntax.

For TCP/IP connections, the hostDescription field is required.

However, the hostDescription field can be omitted in some scenarios. For example:

  • For local Unix socket connections:

    jdbc:mariadb:///database?localSocket=/var/lib/mysql/mysql.sock
    
  • For local named pipe connections:

    jdbc:mariadb:///database?pipe=mariadb
    

Simple Syntax

The hostDescription simple syntax is as follows:

<host>:<port>
  • Requires an IP address or Fully Qualified Domain Name (FQDN) to the target node.

  • Accepts optional port number to connect to on the target node.

For example:

jdbc:mariadb://192.0.2.1:3306/database?user=db_user&password=db_user_password

Complex Syntax

The hostDescription complex syntax is as follows:

address=[(type=(master|replica))][(port=<portnumber>)](host=<host>)
  • type sets whether the node is a primary server or a replica

  • port sets the port number on which to connect

  • host sets the IP address or Fully Qualified Domain Name (FQDN) where the node is located

For example:

jdbc:mariadb://address=(type=master)(host=primary1),address=(port=3307)(type=replica)(host=replica1)/database?user=greg&password=pass

Optional Connection Parameters

MariaDB Connector/J supports several optional connection parameters:

Parameter Name

Description

Data Type

Default Value

Version Added

autoReconnect

Defines whether the connector automatically reconnects after a connection failure.

boolean

false

1.2.0

connectTimeout

Defines the connect timeout value in milliseconds. When set to 0, there is no connect timeout.

int

30000

1.1.8

failOnReadOnly

Defines whether an exception is thrown when only read-only servers are available.

boolean

false

1.2.0

failoverLoopRetries

Applies only when HA mode is specified. Defines the number of times the connector silently loops through available hosts and attempts to reconnect after a connection failure. Between loops, the connector will pause for 250 ms if no servers are available. When set to 0, the connector does not loop through available hosts or attempt to reconnect.

int

120

1.1.8

localSocket

Defines the Unix socket file to use for connections to localhost via Unix domain socket.

string

1.1.4

localSocketAddress

Defines the hostname or IP address to use for the connection socket when connecting to localhost via Unix domain socket.

string

1.1.8

password

Defines the password of the user account to connect with.

string

1.0.0

passwordCharacterEncoding

Defines the character set used to encode the password. When not set, the connector uses the platform's default character set.

string

1.5.9

pipe

For Windows. Defines the name of the named pipe to use for connections to localhost via named pipe. Default named pipe name is MySQL.

string

1.1.3

sharedMemory

For Windows. Defines the shared memory base name to use for connections to localhost via shared memory.

string

1.1.4

socketFactory

Defines the class to use for a custom socket factory. Specify the full name of the class that implements javax.net.SocketFactory.

string

1.0.0

socketTimeout

Defines the network socket timeout (SO_TIMEOUT) in milliseconds. When set to 0, there is no socket timeout.

int

0

1.1.8

usePipelineAuth

Defines whether pipelines are used to send internal queries during the initial authentication and connection process. Several queries are executed during this stage. When pipelines are used, all queries are sent simultaneously, and then all results are reads. This approach can decrease overhead and permit faster connection creation.

boolean

true

1.6.0

user

Defines the user name of the user account to connect with.

string

Current user

1.0.0

validConnectionTimeout

Defines the valid connection timeout in seconds. When the connector is using multiple hosts and a connection has not been used longer than the configured valid connection timeout, the connector will verify that the connection is still valid. When set to 0, no connection validation is performed.

int

0

1.2.0

Code Example: Connect

The following example program opens a single database connection to a server at the IP address 192.0.2.1 using the user account created in the example setup. If your application requires multiple database connections, see Connection Pools for a more appropriate example.

import java.sql.*;
import java.util.Properties;

public class App {

    public static void main(String[] argv) {

        Properties connConfig = new Properties();
        connConfig.setProperty("user", "db_user");
        connConfig.setProperty("password", "db_user_password");

        try (Connection conn = DriverManager.getConnection("jdbc:mariadb://192.0.2.1:3306", connConfig)) {

            // Use Connection
            // ...
        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}