Python SQLAlchemy簡介及基本用法
SQLAlchemy庫簡單介紹
SQLAlchemy是一個基于Python實現(xiàn)的ORM對象關(guān)系映射框架。
該框架建立在DB API之上,使用關(guān)系對象映射進行數(shù)據(jù)庫操作,將類和對象轉(zhuǎn)換成SQL,然后使用數(shù)據(jù)API執(zhí)行SQL并獲取執(zhí)行結(jié)果。
SQLAlchemy的下載安裝
// 默認從官網(wǎng)下載安裝PyMySQL庫 pip3 install sqlalchemy // 從豆瓣源下載安裝PyMySQL庫 pip3 install sqlalchemy -i https://pypi.douban.com/simple // 從清華源下載安裝PyMySQL庫 pip3 install sqlalchemy -i https://pypi.tuna.tsinghua.edu.cn/simple
SQLAlchemy的組件構(gòu)成
SQLAlchemy ORM組成部分如下: Object Relation Mapping(ORM):對象關(guān)系映射
SQLAlchemy Core組成部分如下: Engine:框架的引擎 Connection Pooling:數(shù)據(jù)庫連接池 Dialect:選擇連接數(shù)據(jù)庫的DB API種類 Schema/Types:架構(gòu)和類型 SQL Exprression Language:SQL表達式語言
SQLAlchemy本身無法操作數(shù)據(jù)庫,其必須以來PYMYSQL等第三方插件驅(qū)動, Dialect用于和數(shù)據(jù)API進行交流,根據(jù)配置文件的不同調(diào)用不同的數(shù)據(jù)庫API, 從而實現(xiàn)對數(shù)據(jù)庫的操作
MySQL-Python mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname> pymysql mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>] MySQL-Connector mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname> cx_Oracle oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...] 更多:http://docs.sqlalchemy.org/en/latest/dialects/index.html
配置數(shù)據(jù)庫連接串
uri: dialect[+driver]://user:password@host/dbname[?key=value..] - dialect:數(shù)據(jù)庫,如:sqlite、mysql、oracle、postgresql等 - driver:數(shù)據(jù)庫驅(qū)動,用于連接數(shù)據(jù)庫,比如pymysql、mysqldb等 - username:數(shù)據(jù)庫用戶 - password:數(shù)據(jù)庫密碼 - host:數(shù)據(jù)庫服務IP地址 - port:數(shù)據(jù)庫服務端口 - database:數(shù)據(jù)庫名
# 實例:MySQL + PyMySQL # MySQL服務端配置信息 DB_INFO = dict( host="127.0.0.1", port=6379, user="admin", password="123456", database="test", charset="utf8" ) # 數(shù)據(jù)庫連接URL格式化 DB_URI = 'mysql+pymysql://{user}:{password}@{host}:{port}/{database}?charset={charset}'.format(**DB_INFO)
創(chuàng)建引擎并連接數(shù)據(jù)庫
engine = create_engine("mysql+pymysql://root:123456@localhost:3306/db4?charset=utf8", max_overflow=0, # 超過連接池大小外最多創(chuàng)建的連接 pool_size=5, # 連接池大小 pool_timeout=30, # 池中沒有線程最多等待的時間,否則報錯 pool_recycle=-1 # 多久之后對線程池中的線程進行一次連接的回收(重置) echo = True # echo參數(shù)為True時,會顯示每條執(zhí)行的SQL語句,可以關(guān)閉 ",max_overflow = 5)
from sqlalchemy import create_engine # 連接地址 DB_URI = 'mysql+pymysql://{user}:{password}@{host}:{port}/{database}?charset={charset}' # 創(chuàng)建引擎 engine = create_engine(DB_URI) # 打開連接 conn = engine.connect() # 執(zhí)行查詢 result = conn.execute('select * from user limit %s offset %s', 10, 2) # 獲取單條數(shù)據(jù) data_line = result.fetchone() # 獲取多條數(shù)據(jù) data_list = result.fetchmany(2) # 獲取全部數(shù)據(jù) data_list = result.fetchall() # 插入數(shù)據(jù)操作,獲取最后行ID last_row_id = result.lastrowid # 關(guān)閉連接 conn.close()
數(shù)據(jù)庫對象映射模型
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker # 數(shù)據(jù)庫連接地址 DB_URI = 'mysql+pymysql://{user}:{password}@{host}:{port}/{database}?charset={charset}' # 創(chuàng)建數(shù)據(jù)庫引擎 engine = create_engine(DB_URI) # 模型基類 Base = declarative_base(engine) session = sessionmaker(engine)() class Student(Base): """功能:學生映射模型類""" __tablename__ = 'Student' id = Column(Integer, primary_key=True, autoincrement=True, comment="主鍵ID") name = Column(String(50), index=True, nullable=True, comment="學生名稱") age = Column(Integer, comment="學生年齡") sex = Column(String(10), comment="學生性別") # 創(chuàng)建全部表,默認自動跳過已存在表 Base.metadata.create_all() # 創(chuàng)建指定表,默認自動跳過已存在表 Base.metadata.create_all(tables=[Student.__table__]) # 刪除全部表,默認自動跳過不存在的表 Base.metadata.drop_all() # 刪除指定表,默認自動跳過不存在的表 Base.metadata.drop_all(tables=[Student.__table__])
到此這篇關(guān)于SQLAlchemy簡介以及基本使用的文章就介紹到這了,更多相關(guān)SQLAlchemy基本使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python?ORM框架之SQLAlchemy?的基礎(chǔ)用法
- Python?flask?sqlalchemy的簡單使用及常用操作
- python flask sqlalchemy連接數(shù)據(jù)庫流程介紹
- python sqlalchemy動態(tài)修改tablename兩種實現(xiàn)方式
- Python+SQLAlchemy輕松實現(xiàn)管理數(shù)據(jù)庫
- 3個Python?SQLAlchemy數(shù)據(jù)庫操作功能詳解
- Python使用SQLAlchemy模塊實現(xiàn)操作數(shù)據(jù)庫
- Python?SQLAlchemy與數(shù)據(jù)庫交互操作完整指南
- Python?SQLAlchemy庫的實現(xiàn)示例
相關(guān)文章
python實現(xiàn)簡易內(nèi)存監(jiān)控
這篇文章主要介紹了python實現(xiàn)簡易內(nèi)存監(jiān)控,每隔3秒獲取系統(tǒng)內(nèi)存,當內(nèi)存超過設(shè)定的警報值時,獲取所有進程占用內(nèi)存并發(fā)出警報聲,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06利用Python批量壓縮png方法實例(支持過濾個別文件與文件夾)
這篇文章主要給大家介紹了關(guān)于利用Python批量壓縮png的相關(guān)資料,文中介紹的方法支持過濾個別文件與文件夾,文中通過示例代碼介紹的非常詳細,需要的朋友們下面跟著小編來一起看看吧。2017-07-07TensorFlow2.0使用keras訓練模型的實現(xiàn)
這篇文章主要介紹了TensorFlow2.0使用keras訓練模型的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02Python tkinter布局與按鈕間距設(shè)置方式
這篇文章主要介紹了Python tkinter布局與按鈕間距設(shè)置方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03