Python提供了多种方式连接和操作数据库,遵循Python DB-API(Database API)规范。
1. 安装数据库接口模块
首先,确保已经安装了适合MySQL的数据库接口模块。对于MySQL,常用的模块是mysqlclient
或pymysql
。可以通过Python的包管理工具pip来安装:
pip install mysqlclient
# 或者
pip install pymysql
2. 导入模块
在Python脚本中,需要导入已安装的数据库模块:
import mysql.connector # 如果使用mysqlclient
# 或者
import pymysql
3. 连接数据库
使用模块提供的连接函数来连接数据库。需要提供主机地址、用户名、密码和数据库名:
# 使用mysql.connector
db = mysql.connector.connect(
host="localhost",
user="your_username",
passwd="your_password",
database="your_database"
)
# 使用pymysql
db = pymysql.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor # 可使用字典方式获取数据
)
4. 创建游标对象
游标对象用于执行SQL语句和获取结果:
cursor = db.cursor()
5. 执行SQL语句
使用游标的execute()
方法执行SQL查询或命令:
# 例如,执行一个查询
cursor.execute("SELECT VERSION()")
# 执行插入操作
insert_sql = "INSERT INTO your_table (column1, column2) VALUES (%s, %s)"
values = (value1, value2)
cursor.execute(insert_sql, values)
6. 获取查询结果
对于SELECT语句,可以使用游标的fetchone()
、fetchmany()
或fetchall()
方法来获取结果集:
# 获取单条数据
data = cursor.fetchone()
# 获取多条数据
data = cursor.fetchmany(size=10)
# 获取所有数据
data = cursor.fetchall()
7. 错误处理
使用try-except块来处理可能发生的异常:
try:
cursor.execute(sql)
db.commit() # 提交事务
except mysql.connector.Error as err: # mysqlclient的错误处理
print("Error: {}".format(err))
db.rollback() # 发生错误时回滚
# pymysql错误处理类似,但异常类型可能不同
8. 提交和回滚事务
对于需要事务的数据库操作,使用commit()
方法提交更改,或使用rollback()
进行回滚。
9. 关闭游标和连接
操作完成后,关闭游标和数据库连接:
cursor.close()
db.close()