MariaDB Database Connections

In this lesson, you will learn how to connect the Maria database in Python using the mariadb module.
To connect to a maria database, instead of using the pyodbc.connect() method, use the mariadb.connect() method.

First import the MariaDB module:

import mariadb

Code Explanation

LineDescription
1-5Specify information about the database connection.
10Defines a method named connectMariaDB().
11 + 22The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
12-18Creates a MariaDB Connection object.
By default the standard connection class mariadb.connections.Connection will be created.
Parameter connectionclass specifies a subclass of mariadb.Connection object. If not specified default will be used.
20Return MariaDBConnection object.
22-24If an error occurs in the try block, it is intercepted and an error message is output via the error object e.
server = 'server_name'
database = 'db_name'
username = 'user_name'
password = 'user_pw'
driver = '{ODBC Driver 17 for SQL Server}'

# --------------------------------------------------
# MariaDB Database Connection
# --------------------------------------------------
def connectMariaDB():
    try:
        connection = mariadb.connect(
            user=username,
            password=password,
            host=server,
            port=3306,
            database=database,
            ssl={'ssl' : {'ca': 'BaltimoreCyberTrustRoot.crt.pem'}}
        )
        return connection

    except mariadb.Error as e:
        print("Error while connecting to Maria Database: ", e)
        sys.exit(1)