Skip to main content

Menu

Webinar

Built for the Agentic Era: Introducing MariaDB Enterprise Platform 2027

Register now

Developer

How to connect Python programs to MariaDB

By Rob Hedgpeth

6 min read
Share
$ pip3 install mariadb
# Module Imports
import mariadb
import sys

# Connect to MariaDB Platform
try:
    conn = mariadb.connect(
        user="db_user",
        password="db_user_passwd",
        host="192.0.2.1",
        port=3306,
        database="employees"

    )
except mariadb.Error as e:
    print(f"Error connecting to MariaDB Platform: {e}")
    sys.exit(1)

# Get Cursor
cur = conn.cursor()
cur.execute(
    "SELECT first_name,last_name FROM employees WHERE first_name=?", 
    (some_name,))
# Print Result-set
for (first_name, last_name) in cur:
    print(f"First Name: {first_name}, Last Name: {last_name}")
cur.execute(
"INSERT INTO employees "
"(emp_no, birth_date, first_name, last_name, gender, hire_date) "
"VALUES (?, ?, ?, ?, ?, ?)"
,
(new_emp_no, "1990-01-15", "Maria", "DB", "F", "2024-01-01"))
conn.commit()
# Enable Auto-Commit
conn.autocommit = True
try:
    cursor.execute("some MariaDB query"))
except mariadb.Error as e:
    print(f"Error: {e}")
# Close Connection
conn.close()
#!/usr/bin/python
import mariadb
import sys

try:
conn = mariadb.connect(
user="db_user",
password="db_user_passwd",
host="localhost",
database="employees")
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)

cur = conn.cursor()

# retrieving information
some_name = "Georgi"
cur.execute("SELECT first_name, last_name FROM employees WHERE first_name=?", (some_name,))

for first_name, last_name in cur:
print(f"First name: {first_name}, Last name: {last_name}")

# inserting information
cur.execute("SELECT MAX(emp_no) FROM employees")
(max_emp_no,) = cur.fetchone()
new_emp_no = max_emp_no + 1

try:
cur.execute(
"INSERT INTO employees "
"(emp_no, birth_date, first_name, last_name, gender, hire_date) "
"VALUES (?, ?, ?, ?, ?, ?)",
(new_emp_no, "1990-01-15", "Maria", "DB", "F", "2024-01-01"))
except mariadb.Error as e:
print(f"Error: {e}")

conn.commit()
print(f"Inserted employee with emp_no: {new_emp_no}")

conn.close()