Using Python to Operate MariaDB

To operate the MariaDB database using Python, Python libraries such as pymysql or mysql connector Python are required. The following is a complete Python code example using pymysql: 1. Install pymysql: pip install pymysql 2. Connect to the MariaDB database: python import pymysql #Establishing a database connection conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', database='test') #Create a cursor object cursor = conn.cursor() 3. Insert data: python #Insert a piece of data sql = "INSERT INTO users (name, email) VALUES (%s, %s)" values = ('John Doe', 'john@example.com') cursor.execute(sql, values) #Commit transaction conn.commit() #Obtain the ID of the inserted data print("Inserted ID:", cursor.lastrowid) 4. Query data: python #Query data sql = "SELECT * FROM users" cursor.execute(sql) #Get all query results results = cursor.fetchall() #Traverse result for row in results: id = row[0] name = row[1] email = row[2] print(f"ID: {id}, Name: {name}, Email: {email}") 5. Modify data: python #Modify data sql = "UPDATE users SET email = %s WHERE id = %s" values = ('new-email@example.com', 1) cursor.execute(sql, values) #Commit transaction conn.commit() 6. Delete data: python #Delete data sql = "DELETE FROM users WHERE id = %s" values = (1,) cursor.execute(sql, values) #Commit transaction conn.commit() 7. Close connection: python #Close Cursor cursor.close() #Close database connection conn.close() The above code example can help you connect to the MariaDB database and perform data insertion, query, modification, and deletion operations. According to your actual situation, you can adjust the table name, fields, and query conditions in the example.