爱心代码示例的Python实现Python实战:MySQL数据库操作全流程详解
在Python中操作MySQL数据库,通常使用MySQL Connector
库或SQLAlchemy
库。下面是一个使用MySQL Connector
进行数据库操作的完整示例。请确保你的系统已经安装了mysql-connector-python
库,可以通过pip install mysql-connector-python
来安装。
以下是一个关于如何连接到MySQL数据库并进行基本CRUD(创建、读取、更新、删除)操作的示例:
import mysql.connector
from mysql.connector import Error
# 连接到MySQL数据库
def create_connection():
try:
connection = mysql.connector.connect(
host='localhost', # 替换为你的数据库主机地址
user='your_username', # 替换为你的数据库用户名
password='your_password', # 替换为你的数据库密码
database='your_database_name' # 替换为你的数据库名
)
if connection.is_connected():
print("Connected to MySQL database")
return connection
except Error as e:
print(f"Error: {e}")
return None
# 创建表
def create_table(connection):
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL,
gender ENUM('Male', 'Female') NOT NULL
);
"""
cursor = connection.cursor()
try:
cursor.execute(create_table_query)
connection.commit()
print("Table created successfully")
except Error as e:
print(f"Error creating table: {e}")
# 插入数据
def insert_data(connection):
insert_query = """
INSERT INTO users (name, age, gender) VALUES (%s, %s, %s)
"""
records_to_insert = [
('Alice', 30, 'Female'),
('Bob', 24, 'Male'),
('Charlie', 29, 'Male')
]
cursor = connection.cursor()
try:
cursor.executemany(insert_query, records_to_insert)
connection.commit()
print(cursor.rowcount, "records inserted successfully")
except Error as e:
print(f"Error inserting data: {e}")
# 查询数据
def read_data(connection):
select_query = "SELECT * FROM users"
cursor = connection.cursor()
try:
cursor.execute(select_query)
records = cursor.fetchall()
print("Records in the users table:")
for row in records:
print(row)
except Error as e:
print(f"Error reading data: {e}")
# 更新数据
def update_data(connection):
update_query = """
UPDATE users SET age = %s WHERE name = %s
"""
data = (28, 'Alice')
cursor = connection.cursor()
try:
cursor.execute(update_query, data)
connection.commit()
print(cursor.rowcount, "record(s) updated successfully")
except Error as e:
print(f"Error updating data: {e}")
# 删除数据
def delete_data(connection):
delete_query = "DELETE FROM users WHERE name = %s"
data = ('Charlie',)
cursor = connection.cursor()
try:
cursor.execute(delete_query, data)
connection.commit()
print(cursor.rowcount, "record(s) deleted successfully")
except Error as e:
print(f"Error deleting data: {e}")
# 主函数
def main():
connection = create_connection()
if connection is not None:
create_table(connection)
insert_data(connection)
read_data(connection)
update_data(connection)
read_data(connection)
delete_data(connection)
read_data(connection)
connection.close()
if __name__ == "__main__":
main()
说明:
- 连接到数据库: 使用
mysql.connector.connect()
方法连接到MySQL数据库。 - 创建表: 使用SQL语句创建
users
表。 - 插入数据: 使用
executemany()
方法批量插入数据。 - 查询数据: 使用
execute()
方法执行查询并遍历结果。 - 更新数据: 使用
execute()
方法更新特定记录。 - 删除数据: 使用
execute()
方法删除特定记录。
请根据你的实际需求替换数据库连接信息,并确保在执行此代码之前MySQL服务器正在运行。