Python MySQL Database Tutorial: Connect, Create, Insert, Update, Delete
Here is a sample code that demonstrates how to connect to a MySQL database using Python:
import mysql.connector
# Connect to MySQL database
mydb = mysql.connector.connect(
host='localhost',
user='yourusername',
password='yourpassword',
database='yourdatabase'
)
# Create a cursor object
mycursor = mydb.cursor()
# Create a table if it does not exist
mycursor.execute('CREATE TABLE IF NOT EXISTS customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))')
# Insert a record into the table
sql = 'INSERT INTO customers (name, address) VALUES (%s, %s)'
val = ('John', 'Highway 21')
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, 'record inserted.')
# Select all records from the table
mycursor.execute('SELECT * FROM customers')
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# Update a record in the table
sql = 'UPDATE customers SET address = %s WHERE name = %s'
val = ('Canyon 123', 'John')
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, 'record(s) updated.')
# Delete a record from the table
sql = 'DELETE FROM customers WHERE address = %s'
val = ('Highway 21',)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, 'record(s) deleted.')
This code creates a connection to a MySQL database, creates a table if it does not exist, inserts a record into the table, selects all records from the table, updates a record in the table, and deletes a record from the table.
原文地址: https://www.cveoy.top/t/topic/lEgo 著作权归作者所有。请勿转载和采集!