【什么是ORM】
ORM 全稱是(Object Relational Mapping)表示對象關系映射; 通俗理解可以理解為編程語言的虛擬數據庫;
【理解ORM】
用戶地址信息數據庫表與對象的映射

【ORM的重要特性】
1.面向對象的編程思想,方便擴充
2. 少寫(幾乎不寫)sql,提升開發效率
3.支持多種類型的數據庫(常用的mysql,pg,oracle等等),方便切換
4.ORM技術已經相當成熟,能解決絕大部分問題
【ORM模型框架的選擇】

【SQLAlchemy ORM模型】
眾所周知,ORM框架模型可選擇的有很多,那么我們這邊選擇了SQLAlchemy 模型框架
pip install SQLAlchemy 安裝sql alchemy; 也可以指定版本號pip install SQLAlchemy ==1.4.17
import sqlalcherm; sqlalchemy.__version__; 驗證是否安裝成功及版本號;
【SQL Alchemy的使用】
一.開始連接數據庫
二.聲明ORM模型基類
三.實現ORM模型類
四.同步數據庫表
開始連接數據庫
- 延遲連接(Lazy Connecting)——只有在真正操作數據庫的時候,才會連接數據庫
- 連接代碼示例
from sqlalchemy import create_engine
create_engine("mysql://root:@127.0.0.1:3306/school?charset=utf8,echo=True,future=True")
create_engine 參數解釋
- url(默認第一個參數)——連接到哪種類型的數據庫,如:mysql;以哪種數據庫連接器(驅動)來連接數據庫
- echo——是否輸出logging(日志)信息,會把日志都打印出來
- future使用SQLAlchemy2.0 API風格
SQLAlchemy配置

當密碼中含有特殊字符時,怎么處理?
話不多說,見下方代碼
from urllib.parse import quote_plus
如果密碼里有特殊字符時,這邊需要導入一個類來處理
password_formatted= quote.plus("mima%mima")
把處理后的密碼粘貼到上方的sqlalchemy配置中,即可
聲明ORM模型基類
from sqlalchemy.orm import declarative_base
聲明這個基類
Base = declarative_base()
【實現ORM模型類】
如何實現? 我們需要寫1個類去繼承他
然后還需要設立1個屬性
from sqlalchemy import Column, Integer, String, DateTime
class Student(Base):
"""學生信息表"""
__tablename__ = 'student'
id = Column(Integer, name='id', primary_key=True)
stu_no = Column(Integer, nullable=False, comment='學號')
stu_name = Column(String(16), nullable=False, comment='姓名')
created_at = Column(DateTime)
1.需要在同步之前保證 數據庫中有這個庫,如果沒有,則需要手動創建
2 創建表,刪除表
from orm_connect_example import Base ,engine
# 創建表
Base.metadata.create_all(engine)
#刪除表
Base.metadata.drop_all(engine)
【ORM對應的模型字段類型】


【代碼示例】
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String, DateTime
# 第一步,準備連接
engine = create_engine('mysql://root:@10.72.100.1:8081/test_database_1?charset=utf8',echo=True)
# 第二步,聲明ORM模型的基類
Base = declarative_base()
# 第三步,實現ORM模型類
class Student(Base):
"""學生信息表"""
__tablename__ = 'student'
id = Column(Integer, name='id', primary_key=True)
stu_no = Column(Integer, nullable=False, comment='學號')
stu_name = Column(String(16), nullable=False, comment='姓名')
created_at = Column(DateTime)
#第四步 同步數據庫表
def create_table()
"""同步數據庫表"""
# 新建表
Base.metadata.create_all(bind=engine)
# 刪除表
Base.metadata.drop_all(bind=engine)
到此這篇關于ORM模型框架操作mysql數據庫的方法的文章就介紹到這了,更多相關ORM模型框架內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Laravel框架Eloquent ORM簡介、模型建立及查詢數據操作詳解
- django框架面向對象ORM模型繼承用法實例分析
- MySql用DATE_FORMAT截取DateTime字段的日期值
- mysql數據庫中的information_schema和mysql可以刪除嗎?