使用SQLAlchemy操作MySQL
使用SQLAlchemy操作MySQL
SQLAlchemy是Python编程语言下的一款开源软件,提供了SQL工具包及对象关系映射(ORM)工具,使用MIT许可证发行。SQLAlchemy首次发行于2006年2月,并迅速地在Python社区中最广泛使用的ORM工具之一,不亚于Django的ORM框架。
本文将介绍如何使用SQLAlchemy操作MySQL,完成基础的表创建,表格数据的新增、查询、修改、删除(CRUD)等操作。
首先我们需要确认当前的Python环境下已经安装sqlalchemy和pymysql模块。
新建表格
我们使用本地的MySQL数据库,数据库为orm_test。新建一张users表,字段为id,name,age,place。完整的Python代码(create_table.py
)如下:
# -*- coding: utf-8 -*-
# author: Jclian91
# place: Sanya, Hainan
# time: 12:46
from sqlalchemy.dialects.mysql import INTEGER, VARCHAR
from sqlalchemy import Column
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# users表结构
class Users(Base):
__tablename__ = 'users'
id = Column(INTEGER, primary_key=True)
name = Column(VARCHAR(256), nullable=False)
age = Column(INTEGER)
place = Column(VARCHAR(256), nullable=False)
def __init__(self, id, name, age, place):
self.id = id
self.name = name
self.age = age
self.place = place
def init_db():
engine = create_engine(
"mysql+pymysql://root:@localhost:3306/orm_test",
encoding= "utf-8",
echo=True
)
Base.metadata.create_all(engine)
print('Create table successfully!')
if __name__ == '__main__':
init_db()
运行后,生成的users表结构如下:
数据插入
接着我们插入几条测试数据,完整的代码(db_insert.py
)如下:
# -*- coding: utf-8 -*-
# author: Jclian91
# place: Sanya, Hainan
# time: 12:52
from create_table import Users
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
def insert_data():
# 初始化数据库连接
engine = create_engine("mysql+pymysql://root:@localhost:3306/orm_test", encoding="utf-8")
# 创建DBSession类型
DBSession = sessionmaker(bind=engine)
# 创建session对象
session = DBSession()
# 插入单条数据
# 创建新User对象
new_user = Users(id=1, name='Jack', age=25, place='USA')
# 添加到session
session.add(new_user)
# 提交即保存到数据库
session.commit()
# 插入多条数据
user_list= [Users(id=2, name='Green', age=26, place='UK'),
Users(id=3, name='Alex', age=31, place='GER'),
Users(id=4, name='Chen', age=52, place='CHN'),
Users(id=5, name='Zhang', age=42, place='CHN')
]
session.add_all(user_list)
session.commit()
# 关闭session
session.close()
print('insert into db successfully!')
if __name__ == '__main__':
insert_data()
运行程序后,表格中的数据如下:
数据查询
接下来演示如何进行简单的查询。我们需要查询place为CHN的人名,完整的Python代码(db_query)如下:
# -*- coding: utf-8 -*-
# author: Jclian91
# place: Sanya, Hainan
# time: 12:52
from create_table import Users
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
def query_data():
# 初始化数据库连接
engine = create_engine("mysql+pymysql://root:@localhost:3306/orm_test", encoding="utf-8")
# 创建DBSession类型
DBSession = sessionmaker(bind=engine)
# 创建session对象
session = DBSession()
# 查询所有place是CHN的人名
# 创建Query查询,filter是where条件
# 调用one()返回唯一行,如果调用all()则返回所有行:
users = session.query(Users).filter(Users.place == 'CHN').all()
print([use.name for use in users])
# 输出:['Chen', 'Zhang']
# 或者用如下查询
users = session.query(Users.name).filter(Users.place == 'CHN').all()
print(users)
# 输出:[('Chen',), ('Zhang',)]
session.close()
if __name__ == '__main__':
query_data()
输出结果如下:
['Chen', 'Zhang']
[('Chen',), ('Zhang',)]
数据更新
接下来我们演示数据更新。我们需要将Jack的place修改为CHN,完整的Python代码(db_update)如下:
# -*- coding: utf-8 -*-
# author: Jclian91
# place: Sanya, Hainan
# time: 12:52
from create_table import Users
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
def update_data():
# 初始化数据库连接
engine = create_engine("mysql+pymysql://root:@localhost:3306/orm_test", encoding="utf-8")
# 创建DBSession类型
DBSession = sessionmaker(bind=engine)
# 创建session对象
session = DBSession()
# 数据更新,将Jack的place修改为CHN
update_obj = session.query(Users).filter(Users.name=='Jack').update({"place":"CHN"})
session.commit()
session.close()
print("Update data successfully!")
if __name__ == '__main__':
update_data()
更新后的表格数据如下:
数据删除
接着我们演示数据删除。我们需要将Jack的记录删除,完整的Python代码(db_delete.py)如下:
# -*- coding: utf-8 -*-
# author: Jclian91
# place: Sanya, Hainan
# time: 12:52
from create_table import Users
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
def delete_data():
# 初始化数据库连接
engine = create_engine("mysql+pymysql://root:@localhost:3306/orm_test", encoding="utf-8")
# 创建DBSession类型
DBSession = sessionmaker(bind=engine)
# 创建session对象
session = DBSession()
# 数据更新,将Jack的记录删除
update_obj = session.query(Users).filter(Users.name=='Jack').delete()
session.commit()
session.close()
print("Delete data successfully!")
if __name__ == '__main__':
delete_data()
运行程序后,表格中的数据如下:
皮豆设计(logo设计神器):http://pidou.cn