Python SQLAlchemy簡介及基本用法
SQLAlchemy庫簡單介紹
SQLAlchemy是一個基于Python實現(xiàn)的ORM對象關(guān)系映射框架。
該框架建立在DB API之上,使用關(guān)系對象映射進(jìn)行數(shù)據(jù)庫操作,將類和對象轉(zhuǎn)換成SQL,然后使用數(shù)據(jù)API執(zhí)行SQL并獲取執(zhí)行結(jié)果。
SQLAlchemy的下載安裝
// 默認(rèn)從官網(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表達(dá)式語言
SQLAlchemy本身無法操作數(shù)據(jù)庫,其必須以來PYMYSQL等第三方插件驅(qū)動, Dialect用于和數(shù)據(jù)API進(jìn)行交流,根據(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ù)庫服務(wù)IP地址 - port:數(shù)據(jù)庫服務(wù)端口 - database:數(shù)據(jù)庫名
# 實例:MySQL + PyMySQL
# MySQL服務(wù)端配置信息
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 # 多久之后對線程池中的線程進(jìn)行一次連接的回收(重置)
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):
"""功能:學(xué)生映射模型類"""
__tablename__ = 'Student'
id = Column(Integer, primary_key=True, autoincrement=True, comment="主鍵ID")
name = Column(String(50), index=True, nullable=True, comment="學(xué)生名稱")
age = Column(Integer, comment="學(xué)生年齡")
sex = Column(String(10), comment="學(xué)生性別")
# 創(chuàng)建全部表,默認(rèn)自動跳過已存在表
Base.metadata.create_all()
# 創(chuàng)建指定表,默認(rèn)自動跳過已存在表
Base.metadata.create_all(tables=[Student.__table__])
# 刪除全部表,默認(rèn)自動跳過不存在的表
Base.metadata.drop_all()
# 刪除指定表,默認(rèn)自動跳過不存在的表
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)文章
在pycharm上mongodb配置及可視化設(shè)置方法
今天小編就為大家分享一篇在pycharm上mongodb配置及可視化設(shè)置方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11
Python BeautifulReport可視化報告代碼實例
這篇文章主要介紹了Python BeautifulReport可視化報告代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04
python批量實現(xiàn)Word文件轉(zhuǎn)換為PDF文件
這篇文章主要為大家詳細(xì)介紹了python批量實現(xiàn)Word文件轉(zhuǎn)換為PDF文件的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03
jupyter-lab設(shè)置自啟動及遠(yuǎn)程連接開發(fā)環(huán)境
本文主要介紹了jupyter-lab設(shè)置自啟動及遠(yuǎn)程連接開發(fā)環(huán)境,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02

