connect()

Establishes a connection to a database server and returns a connection object.

See also: MariaDB Connector/Python 1.0

DETAILS

The connection parameters are provided as a set of keyword arguments:

host

The host name or IP address of the database server.

user

The username used to authenticate with the database server.

password

The password of the given user.

database

The database name to use when connecting with the database server.

port

The port number of the database server. If not specified the default value of 3306 will be used.

unix_socket

The location of the unix socket file to use instead of using an IP port to connect. If socket authentication is enabled, this can also be used in place of a password.

connect_timeout

The connect timeout in seconds.

read_timeout

The read timeout in seconds.

write_timeout

The write timeout in seconds.

local_infile

Enables or disables the use of LOAD DATA LOCAL INFILE statements.

compress

Uses the compressed protocol for client server communication. If the server doesn't support compressed protocol, the default protocol will be used.

init_command

Specifies one or more commands to execute when connecting and reconnecting to the database server.

default_file

Read options from the specified option file. If the file is an empty string, the default configuration files are used.

default_group

Read options from the specified group instead of "mysql".

ssl_key

Defines a path to a private key file to use for TLS. This option requires that you use the absolute path, not a relative path. The specified key must be in PEM format.

ssl_cert

Defines a path to the X.509 certificate file to use for TLS. This option requires that you use the absolute path, not a relative path. The X.509 certificate must be in PEM format.

ssl_ca

Defines a path to a PEM file that should contain one or more X.509 certificates for trusted Certificate Authorities (CAs) to use for TLS. This option requires that you use the absolute path, not a relative path.

ssl_capath

Defines a path to a directory with one or more PEM files that contain an X.509 certificate for trusted Certificate Authorities (CA).

ssl_cipher

Defines a list of permitted cipher suites to use for TLS.

ssl_crl_path

Defines a path to a PEM file that should contain one or more revoked X.509 certificates to use for TLS. This option requires that you use the absolute path, not a relative path.

ssl_verify_server_cert

Enables server certificate verification.

ssl_enforce

The connection must use TLS security or it will fail.

username

Alias for the user parameter.

passwd

Alias for the password parameter.

db

Alias for the database parameter.

autocommit

Whether to enable auto-committing transactions.

converter

Configures user-defined data type conversions using a dict containing FIELD_TYPE and conversion functions.

EXAMPLES

The following will connect to a localhost database using the default port and the "root" user and the supplied password:

import sys
import mariadb

try:
    conn = mariadb.connect(
        host = '127.0.0.1',
        user = 'db_user',
        password = 'db_password',
        )
except mariadb.Error as err:
    # Deal with the connection error in whatever way you like:
    print(err, file=sys.stderr)
    sys.exit(1)

# Use the connection here...

conn.close()

Unix Socket Connections

Users configured to use the unix_socket authentication plugin can authorize the connection through the socket. The following code will authorize the user to connect to a local Server without needing to specify a password string:

conn = mariadb.connect(
    host = 'localhost',
    user = 'db_user',
    unix_socket = '/var/run/mysqld/mysqld.sock',
    )

Note that the connect() method is also callable via an existing connection object.

Data Type Conversion

In cases where you would like to use a non-default data type in your code, you can configure a dict of data type conversion functions and pass it to the converter option on the connection.

For instance, configure the connection to return an alternate date type on TIME columns:

  1. Create an example table and use the NOW() function to add a value:

    CREATE TABLE test.time_example (current_time TIME);
    
    INSERT INTO test.time_example VALUES (NOW())
    
  2. In your Python code, configure a conversion function:

    # Module Imports
    import datetime
    
    # DateTime Conversion Function
    def timedelta_to_time(sec):
       """Conversion function renders a timedelta return type
       to Python time"""
       return (datetime.datetime.min + sec).time()
    
  3. Configure the connection converter:

    # Module Imports
    from mariadb.constants import FIELD_TYPE
    
    # Converter
    converter = {**{FIELD_TYPE.TIME: timedelta_to_time}}
    
  4. Then, create a connection with the convert and one without, then execute the example query:

    import sys
    import mariadb
    
    try:
    
        # Connection without Converter
        conn_without_converter = mariadb.connect(
            host = '127.0.0.1',
            user = 'db_user',
            password = 'db_password')
    
        conn_with_converter = mariadb.connect(
            host = '127.0.0.1',
            user = 'db_user',
            password = 'db_password',
            converter=converter)
    
        for conn in [conn_without_converter, conn_with_converter]:
    
            # Get Cursor
            cur = conn.cursor()
    
            # Execute Query
            cur.execute("SELECT * FROM test.time_example;")
    
            for row in cur:
               print(row)
    
            conn.close()
    
    except mariadb.Error as err:
        # Deal with the connection error in whatever way you like:
        print(err, file=sys.stderr)
        sys.exit(1)
    

In the example, two connections are established, one without the converter function and one with the converter function. It then loops over each connection, retrieves a cursor and executes a SELECT statement, printing the results to stdout:

(datetime.timedelta(seconds=45584),)
(datetime.time(12, 39, 44)

The first connection is made without the converter function, so the query returns the standard datetime.timedelta for the TIME column. The second uses the converter function to return a datetime.time instead.