您好,登錄后才能下訂單哦!
如何在python中使用SQLAlchemy對(duì)MySQL數(shù)據(jù)庫進(jìn)行操作?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
首先我們需要確認(rèn)當(dāng)前的Python環(huán)境下已經(jīng)安裝sqlalchemy和pymysql模塊。
新建表格
我們使用本地的MySQL數(shù)據(jù)庫,數(shù)據(jù)庫為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表結(jié)構(gòu) 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()
運(yùn)行后,生成的users表結(jié)構(gòu)如下:
數(shù)據(jù)插入
接著我們插入幾條測試數(shù)據(jù),完整的代碼(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(): # 初始化數(shù)據(jù)庫連接 engine = create_engine("mysql+pymysql://root:@localhost:3306/orm_test", encoding="utf-8") # 創(chuàng)建DBSession類型 DBSession = sessionmaker(bind=engine) # 創(chuàng)建session對(duì)象 session = DBSession() # 插入單條數(shù)據(jù) # 創(chuàng)建新User對(duì)象 new_user = Users(id=1, name='Jack', age=25, place='USA') # 添加到session session.add(new_user) # 提交即保存到數(shù)據(jù)庫 session.commit() # 插入多條數(shù)據(jù) 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() # 關(guān)閉session session.close() print('insert into db successfully!') if __name__ == '__main__': insert_data()
運(yùn)行程序后,表格中的數(shù)據(jù)如下:
數(shù)據(jù)查詢
接下來演示如何進(jìn)行簡單的查詢。我們需要查詢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(): # 初始化數(shù)據(jù)庫連接 engine = create_engine("mysql+pymysql://root:@localhost:3306/orm_test", encoding="utf-8") # 創(chuàng)建DBSession類型 DBSession = sessionmaker(bind=engine) # 創(chuàng)建session對(duì)象 session = DBSession() # 查詢所有place是CHN的人名 # 創(chuàng)建Query查詢,filter是where條件 # 調(diào)用one()返回唯一行,如果調(diào)用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()
輸出結(jié)果如下:
['Chen', 'Zhang']
[('Chen',), ('Zhang',)]
數(shù)據(jù)更新
接下來我們演示數(shù)據(jù)更新。我們需要將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(): # 初始化數(shù)據(jù)庫連接 engine = create_engine("mysql+pymysql://root:@localhost:3306/orm_test", encoding="utf-8") # 創(chuàng)建DBSession類型 DBSession = sessionmaker(bind=engine) # 創(chuàng)建session對(duì)象 session = DBSession() # 數(shù)據(jù)更新,將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()
更新后的表格數(shù)據(jù)如下:
數(shù)據(jù)刪除
接著我們演示數(shù)據(jù)刪除。我們需要將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(): # 初始化數(shù)據(jù)庫連接 engine = create_engine("mysql+pymysql://root:@localhost:3306/orm_test", encoding="utf-8") # 創(chuàng)建DBSession類型 DBSession = sessionmaker(bind=engine) # 創(chuàng)建session對(duì)象 session = DBSession() # 數(shù)據(jù)更新,將Jack的記錄刪除 update_obj = session.query(Users).filter(Users.name=='Jack').delete() session.commit() session.close() print("Delete data successfully!") if __name__ == '__main__': delete_data()
運(yùn)行程序后,表格中的數(shù)據(jù)如下:
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。