使用Python操作MySQL数据库的基本步骤如下:
1. 安装库:
pip install pymysql
2. 导入库并创建连接:
import pymysql数据库连接参数host = 'localhost'user = 'root'password = ''database = 'test_db'port = 3306charset = 'utf8'创建连接conn = pymysql.connect(host=host, user=user, password=password, database=database, port=port, charset=charset)
3. 创建游标对象:
创建游标对象cursor = conn.cursor()
4. 执行SQL语句:

创建表sql_create_table = """CREATE TABLE IF NOT EXISTS employees (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL,age INT,department VARCHAR(255))"""cursor.execute(sql_create_table)插入数据sql_insert = "INSERT INTO employees (name, age, department) VALUES (%s, %s, %s)"data = ('John Doe', 30, 'Sales')cursor.execute(sql_insert, data)更新数据sql_update = "UPDATE employees SET age = %s WHERE name = %s"data = (31, 'John Doe')cursor.execute(sql_update, data)删除数据sql_delete = "DELETE FROM employees WHERE name = %s"data = ('John Doe', )cursor.execute(sql_delete, data)
5. 提交事务:
提交事务conn.commit()
6. 关闭游标和连接:
关闭游标cursor.close()关闭连接conn.close()
以上步骤展示了如何使用Python和`pymysql`库进行基本的数据库操作,包括创建表、插入、更新和删除数据。请根据实际需求调整代码中的参数和SQL语句
