import mysql.connector from mysql.connector import errorcode # Define database connection details db_config = { 'user': 'neuer', # Replace with your MariaDB username 'password': 'S3raph1n!', # Replace with your MariaDB password 'host': 'mariadb', # The service name of your MariaDB container } # Initialize connection and cursor variables conn = None cursor = None try: # Connect to MariaDB server conn = mysql.connector.connect(**db_config) cursor = conn.cursor() print("Connected to MariaDB server") # Force the session to use utf8mb4_general_ci collation cursor.execute("SET SESSION collation_connection = 'utf8mb4_general_ci'") cursor.execute("SET NAMES 'utf8mb4' COLLATE 'utf8mb4_general_ci'") print("Session collation set to utf8mb4_general_ci") # Drop the existing database if it exists cursor.execute("DROP DATABASE IF EXISTS test_db") print("Existing 'test_db' database dropped.") # Create a new database with utf8mb4_general_ci collation cursor.execute("CREATE DATABASE test_db CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci") print("Database 'test_db' created with utf8mb4_general_ci collation.") # Select the newly created database conn.database = 'test_db' # Ensure all tables in this database use utf8mb4_general_ci collation create_table_query = ( "CREATE TABLE employees (" " id INT AUTO_INCREMENT PRIMARY KEY," " first_name VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci," " last_name VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci," " hire_date DATE" ") ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci" ) cursor.execute(create_table_query) print("Table 'employees' created with utf8mb4_general_ci collation.") # Insert a sample record add_employee_query = ( "INSERT INTO employees (first_name, last_name, hire_date) " "VALUES (%s, %s, %s)" ) employee_data = ('John', 'Doe', '2024-08-14') cursor.execute(add_employee_query, employee_data) conn.commit() print("Sample record inserted into 'employees' table.") # Retrieve and display the inserted record cursor.execute("SELECT * FROM employees") rows = cursor.fetchall() for row in rows: print(f"ID: {row[0]}, First Name: {row[1]}, Last Name: {row[2]}, Hire Date: {row[3]}") 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) finally: # Close cursor and connection only if they were successfully created if cursor: cursor.close() if conn: conn.close() print("Connection closed.")