Connect with MariaDB Connector/Python

Overview

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

Connections

Connections are managed using the following Python class:

Class

Description

connection

Represents a connection to MariaDB Enterprise.

Connections are created, used, and managed using the following Connection class functions:

Function

Description

connect()

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

cursor()

Returns a new cursor object for the current connection.

change_user()

Changes the user and default database of the current connection.

reconnect()

Tries to make a connection object active again by reconnecting to the server using the same credentials which were specified in connect() method.

close()

Closes the connection.

Code Example: Connect

The following code example connects to a server at the IP address 192.0.2.1 using the database and user account created in Setup for Examples:

# Module Import
import mariadb
import sys

# Instantiate Connection
try:
   conn = mariadb.connect(
      user="connpy_test",
      password="passwd",
      host="192.0.2.1",
      port=3306)

   # Use Connection

   # Close Connection
   conn.close()

except mariadb.Error as e:
   print(f"Error connecting to MariaDB Enterprise: {e}")
   sys.exit(1)
  • The connect() function returns an instance of the connection class, which is assigned to the conn variable.

  • The connection attributes are passed as keyword arguments to the connect() function.

  • When you are done with a connection, close it to free resources. Close the connection using the close() method.

Multiple Connections

Instantiating the connection class creates a single connection to MariaDB Enterprise. Applications that require multiple connections may benefit from pooling connections.

Close a Connection

MariaDB Connector/Python closes the connection as part of the class's destructor, which is executed when an instance of the class goes out of scope. This can happen in many cases, such as:

  • When the program exits

  • When the connection instance is defined in the local scope of a function, and the function returns

  • When the connection instance is defined as an attribute of a custom class's instance, and the custom class's instance goes out of scope

Connections can also be explicitly closed using the close() method, which is helpful when the connection is no longer needed, but the variable is still in scope.