使用 pymysql 库操作 MySQL
安装 pymysql。
pip install pymysql
创建 mysql.json(数据源配置文件)。
{
"host": "localhost",
"user": "root",
"password": "root",
"database": "testdb",
"charset": "utf8"
}
读取配置文件,连接数据库,对数据库做增删改查。
import json
import traceback
import pymysql
# 读取数据源配置文件
with open('mysql.json', encoding='utf-8') as db_json:
con_config = json.load(db_json)
db = pymysql.connect(
host=con_config["host"],
user=con_config["user"],
password=con_config["password"],
database=con_config["database"],
charset=con_config["charset"]
)
cursor = db.cursor()
try:
# 参数统一用 %s 占位
sql = 'UPDATE t2 SET t_id = %s WHERE id = %s'
var = ('新值', 1)
cursor.execute(sql, var)
# 需要提交才能生效
db.commit()
print('update success,row: %s' % cursor.rowcount)
sql = 'SELECT * FROM t2 WHERE id = %s'
# 参数使用 tuple 包装. 当 tuple 只有一个值时, 需要加上“,” , 否则“()”会被认为是优先级运算符
var = (1,)
# 执行sql
cursor.execute(sql, var)
# 获取所有记录
data = cursor.fetchall()
for item in data:
id = item[0]
t_id = item[1]
print('id=%s, t_id=%s' % (id, t_id))
except Exception as e:
traceback.print_exc()
finally:
cursor.close()
db.close()
打印结果如下:
update success,row: 1
id=1, t_id=新值
使用 ORM 框架操作 MySQL
Python 中比较有名的 ORM 框架是 SQLAlchemy ,以下是操作示例。
from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 创建对象的基类
Base = declarative_base()
# 定义类
class Student(Base):
# 表的名字
__tablename__ = 'test_iu'
# 表的结构
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(20))
age = Column(Integer)
# 初始化数据库连接, MySQL 8.0 以上需要添加 auth_plugin 参数
engine = create_engine('mysql+mysqlconnector://root:root@localhost:3306/test5?auth_plugin=mysql_native_password')
DBSession = sessionmaker(bind=engine)
# 获取 session 对象
session = DBSession()
# 1.新增多条记录
for s in ('s4', 's5'):
# 创建对象,添加到 session
session.add(Student(name=s, age=0))
session.commit()
# 2.查询记录,调用all()则查询所有. 这里 name 的字符串比较要使用“==”
stu = session.query(Student).filter(Student.name == 's1').one()
print('name: ', stu.name)
# 3.修改记录. 先查询出要更改的记录, 然后修改对象, 修改完直接 commit 即可
stu = session.query(Student).filter(Student.name == 's1').one()
stu.name = 'new_s1'
session.commit()
# 4. 删除记录. 先查询出要删除的记录,然后调用 delete(), 再 commit 即可
stu = session.query(Student).filter(Student.name == 'new_s1').all()
for s in stu:
session.delete(s)
session.commit()
# 关闭 session
session.close()