網站首頁 編程語言 正文
前言
說到面向對象,大家都不陌生。關系型數據庫也是后端日常用來存儲數據的,但數據庫是關系型的,因此,ORM通過對象模型和數據庫的關系模型之間建立映射,我們就能像操作對象一樣來操作數據庫。 ORM的優點主要是面向對象編程,不需寫原生SQL,用操作對象的方式訪問數據。當然,缺點就是當遇到復雜的操作時,ORM就不那么好寫了,還有就是加了一層映射,執行效率低于原生sql。不過,對于大部分項目來說,這些缺點都是可以接受的。犧牲的性能可以接受;有復雜操作時,實現就用原生SQL,ORM執行罷了。
flask sqlalchemy的配置使用
在python中,常用的ORM工具就是sqlalchemy了。下面就以一個簡單的flask例子來說明吧。
首先,寫一個最簡單的flask項目,代碼如下:
from flask import Flask app = Flask(__name__) @app.route('/') def orm_test(): return "hello"
接下來我們導入ORM配置,添加如下代碼:
from flask_sqlalchemy import SQLAlchemy def orm_config(): url = "mysql+mysqlconnector://{user}:{pwd}@{host}:{port}/{db_name}?charset=utf8" orm_conf = { 'SQLALCHEMY_DATABASE_URI': url } return orm_conf # ORM 設置 app.config.from_mapping(orm_config) db = SQLAlchemy(app)
這樣我們就將ORM配置OK了。
- 然后我們新增一個表table1的model
# model表名 class Table1(db.Model): # 表名 __tablename__ = "table1" id = db.Column(db.Integer, primary_key=True) col = db.Column(db.String(64), nullable=False, unique=True, comment='字段釋義')
以上配置這是在數據源只有一個庫的時候,但很多時候我們還需要訪問別的庫,這時需要在ORM配置和model上做一些設置。
ORM配置中需要用到SQLALCHEMY_BINDS
來添加數據庫, model中__bind_key__
來指定數據庫了。
具體修改如下:
修改ORM配置:
def orm_config(): url = "mysql+mysqlconnector://{user}:{pwd}@{host}:{port}/{db_name}?charset=utf8" # 指定的別庫 other_url = "mysql+mysqlconnector://{user1}:{pwd1}@{host1}:{port1}/{db_name1}?charset=utf8" orm_conf = { 'SQLALCHEMY_DATABASE_URI': url, # 添加別庫 "SQLALCHEMY_BINDS":{ "other_db":other_url }, } return orm_conf
表model指定庫:
class Table2(db.Model): # 指定別庫 __bind_key__ = 'other_db' __tablename__ = "table2" id = db.Column(db.Integer, primary_key=True) col = db.Column(db.String(64), nullable=False, unique=True, comment='字段釋義')
最后,我們在接口中使用下ORM。
@app.route('/') def orm_test(): # 查詢table1數據 rows = Table1.query.filter(Table1.id<5) res = [] for row in rows: dict = { "id": row.id, "col": row.col } res.append(dict) return "hhh"
當我們遇到復雜操作,不知道ORM語法該怎么寫時,還可以直接用原生sql + ORM session execute的方式執行,示例如下:
sql = "select count(*) as cnt from table1 group by col" rows = db.session.execute(sql)
以上例子我們是查詢table1表的id<5的數據。
完整代碼如下:
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) def orm_config(): url = "mysql+mysqlconnector://{user}:{pwd}@{host}:{port}/{db_name}?charset=utf8" other_url = "mysql+mysqlconnector://{user1}:{pwd1}@{host1}:{port1}/{db_name1}?charset=utf8" orm_conf = { 'SQLALCHEMY_DATABASE_URI': url, "SQLALCHEMY_BINDS":{ "other_db":other_url }, } return orm_conf # ORM 設置 app.config.from_mapping(orm_config) db = SQLAlchemy(app) # model表名 class Table1(db.Model): # 表名 __tablename__ = "table1" id = db.Column(db.Integer, primary_key=True) col = db.Column(db.String(64), nullable=False, unique=True, comment='字段釋義') class Table2(db.Model): # 指定庫 __bind_key__ = 'other_db' __tablename__ = "table2" id = db.Column(db.Integer, primary_key=True) col = db.Column(db.String(64), nullable=False, unique=True, comment='字段釋義') @app.route('/') def orm_test(): # 查詢table1數據 rows = Table1.query.filter(Table1.id<5) res = [] for row in rows: dict = { "id": row.id, "col": row.col } res.append(dict) return "hhh" if __name__ =="__main__": app.run()
sqlalchemy的增刪改查
剛開始接觸sqlalchemy時,對于語法不熟悉,寫代碼也是比較痛苦的。這里總結下sqlalchemy常用的語法吧。
查詢數據
# 查詢id<5的數據 q = Table1.query.filter(Table1.id<5) # 查詢過濾用 and、or from sqlalchemy import and_, or_ q = Table1.query.filter(and_(Table1.id<5, Table1.col=='掘金')) q = Table1.query.filter(or_(Table1.id<5, Table1.col=='掘金')) # 查詢過濾用in(語法:model.{字段名}.in_({列表})) q = Table1.query.filter(Table1.id.in_([1,2,3])) # 連表查詢 q = Table1.query.join(Table2, Table2.id==Table1.id) \ .filter(Table1.id<5) # 解析數據 res = {'data': [dict(i) for i in q]} # 查詢數據count count = q.count()
增加數據
row = Table1(id=1, col='掘金') db.session.add(row) db.seesion.commit()
修改數據
row = Table1.query.filter(Table1.id<5) update_data = {"col": "掘金"} row.update(update_data) db.session.commit()
刪除數據
row = Table1.query.filter(Table1.id<5) row.delete() db.session.commit()
備注: 增刪改都要commit()
總結
我們在工程代碼中使用sqlalchemy時,在配置時記得根據實際情況添加相關配置參數,比如連接池的數量、自動回收連接的秒數等等。
原文鏈接:https://juejin.cn/post/7130832178132287496
相關推薦
- 2022-04-10 SpringBoot 導入插件報錯 Cannot resolve plugin org.spring
- 2023-08-01 前端眼里的多線程,專用Worker線程
- 2022-08-27 一文了解Go語言中的函數與方法的用法_Golang
- 2022-04-19 基于HarmonyOS的ArkUI編寫的社區類app(四)———倒計時控制和驗證碼登錄功能的實現
- 2022-12-08 C++?Boost?Any示例分析使用_C 語言
- 2021-12-12 七大經典排序算法圖解_C 語言
- 2022-08-10 C#對WPF數據綁定的菜單插入Seperator分隔_C#教程
- 2022-07-23 C#操作windows系統進程的方法_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支