如何在python中使用SQLAlchemy对MySQL数据库进行操作?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
首先我们需要确认当前的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()
运行程序后,表格中的数据如下:
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。