Files
fhem-extract/scripts/test_database.py
2024-08-15 07:55:00 +00:00

39 lines
1.3 KiB
Python

import mysql.connector
from mysql.connector import errorcode
def connect_to_db():
connection = None # Initialize connection to None
try:
# Establish connection
connection = mysql.connector.connect(
host='mariadb', # Use the container name or the IP address of the host running the container
user='neuer',
password='S3raph1n!',
charset='utf8mb4' # Ensure the connection uses the correct charset
)
# Create a cursor object using the connection
cursor = connection.cursor()
# Set the session collation explicitly
cursor.execute("SET SESSION collation_connection = 'utf8mb4_unicode_ci'")
cursor.execute("SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'")
print("Connected to MariaDB with utf8mb4_unicode_ci collation")
return connection
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
return connection
# Example of using the connection
conn = connect_to_db()
if conn:
# Perform database operations here
conn.close()