minor changes

This commit is contained in:
2024-08-15 07:55:00 +00:00
parent 66e7d70d2a
commit 3692cb01a9

View File

@@ -1,78 +1,38 @@
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
}
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
# Initialize connection and cursor variables
conn = None
cursor = None
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
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.")
# Example of using the connection
conn = connect_to_db()
if conn:
# Perform database operations here
conn.close()