簡介
SQLAlchemy是用Python編程語言開發的一個開源項目。它提供了SQL工具包和ORM(對象關系映射)工具,使用MIT許可證發行。
SQLAlchemy最初在2006年2月發行,發行后便很快的成為Python社區中最廣泛使用的ORM工具之一,絲毫不亞於Django自帶的ORM框架。
SQLAlchemy采用簡單的Python語言,提供高效和高性能的數據庫訪問,實現了完整的企業級持久模型。它的理念是,SQL數據庫的量級和性能比對象集合重要,而對象集合的抽象又重要於表和行。
基本用法
安裝
安裝sqlalchemy
pip3 install sqlalchemy
pip3 install pymysql
本文使用MySQL作為數據庫,使用pymysql作為驅動,因此需要安裝pymysql
連接數據庫
配置信息
在連接數據庫前,需要使用到一些配置信息,然后把它們組合成滿足以下條件的字符串:
dialect+driver://username:password@host:port/database
- dialect:數據庫,如:sqlite、mysql、oracle等
- driver:數據庫驅動,用於連接數據庫的,本文使用pymysql
- username:用戶名
- password:密碼
- host:IP地址
- port:端口
- database:數據庫
HOST = 'localhost'
PORT = 3306
USERNAME = 'root'
PASSWORD = '123456'
DB = 'myclass'
# dialect + driver://username:passwor@host:port/database
DB_URI = f'mysql+pymysql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DB}'
建議將配置信息放到你的配置文件中,如config.py
創建引擎並連接數據庫
from sqlalchemy import create_engine
from config import DB_URI
engine = create_engine(DB_URI) # 創建引擎
conn = engine.connect() # 連接
result = conn.execute('SELECT 1') # 執行SQL
print(result.fetchone())
conn.close() # 關閉連接
創建ORM模型並映射到數據庫中
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from config import DB_URI
engine = create_engine(DB_URI)
Base = declarative_base(engine) # SQLORM基類
session = sessionmaker(engine)() # 構建session對象
class Student(Base):
__tablename__ = 'student' # 表名
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(50))
age = Column(Integer)
sex = Column(String(10))
Base.metadata.create_all() # 將模型映射到數據庫中
執行上面代碼,將會在數據庫中生成對應的映射表student。
新增數據
創建表后,接下來我們要添加數據,代碼如下:
student = Student(name='Tony', age=18, sex='male') # 創建一個student對象
session.add(student) # 添加到session
session.commit() # 提交到數據庫
也可以批量添加數據:
session.add_all([
Student(name='Jane', age=16, sex='female'),
Student(name='Ben', age=20, sex='male')
])
session.commit()
查詢數據
sqlalchemy提供了query()方法來查詢數據
獲取所有數據
item_list = session.query(Student).all()
print(item_list)
for item in item_list:
print(item.name, item.age)
執行結果如下
[<mymodel.Student object at 0x000002A0E6A38088>, <mymodel.Student object at 0x000002A0E6A38208>, <mymodel.Student object at 0x000002A0E6A38288>]
Tony 18
Jane 16
Ben 20
查詢得到的item_list是一個包含多個Student對象的列表
指定查詢列
item_list = session.query(Student.name).all()
print(item_list)
# [('Tony',), ('Jane',), ('Ben',)]
獲取返回數據的第一行
item = session.query(Student.name).first()
print(item)
# ('Tony',)
使用filter()方法進行篩選過濾
item_list = session.query(Student.name).filter(Student.age >= 18).all()
print(item_list)
# [('Tony',), ('Ben',)]
使用order_by()進行排序
item_list = session.query(Student.name, Student.age).order_by(Student.age.desc()).all() # desc()表示倒序
print(item_list)
# [('Ben', 20), ('Tony', 18), ('Jane', 16)]
多個查詢條件(and和or)
# 默認為and, 在filter()中用,分隔多個條件表示and
item_list = session.query(Student.name, Student.age, Student.sex).filter(
Student.age >= 10, Student.sex == 'female'
).all()
print(item_list) # [('Jane', 16, 'female')]
from sqlalchemy import or_
# 使用or_連接多個條件
item_list = session.query(Student.name, Student.age, Student.sex).filter(
or_(Student.age >= 20, Student.sex == 'female')
).all()
print(item_list) # [('Jane', 16, 'female'), ('Ben', 20, 'male')]
equal/like/in
# 等於
item_list = session.query(Student.name, Student.age, Student.sex).filter(
Student.age == 18
).all()
print(item_list) # [('Tony', 18, 'male')]
# 不等於
item_list = session.query(Student.name, Student.age, Student.sex).filter(
Student.age != 18
).all()
print(item_list) # [('Jane', 16, 'female'), ('Ben', 20, 'male')]
# like
item_list = session.query(Student.name, Student.age, Student.sex).filter(
Student.name.like('%To%')
).all()
print(item_list) # [('Tony', 18, 'male')]
# in
item_list = session.query(Student.name, Student.age, Student.sex).filter(
Student.age.in_([16, 20])
).all()
print(item_list) # [('Jane', 16, 'female'), ('Ben', 20, 'male')]
count計算個數
count = session.query(Student).count()
print(count) # 3
切片
item_list = session.query(Student.name).all()[:2]
print(item_list) # [('Tony',), ('Jane',)]
修改數據
修改數據可以使用update()方法,update完成后記得執行session.commit()
# 修改Tony的age為22
session.query(Student).filter(Student.name == 'Tony').update({'age': 22})
session.commit()
item = session.query(Student.name, Student.age).filter(Student.name == 'Tony').first()
print(item)
執行結果如下
('Tony', 22)
刪除數據
刪除數據使用delete()方法,同樣也需要執行session.commit()提交事務
# 刪除名稱為Ben的數據
session.query(Student).filter(Student.name == 'Ben').delete()
session.commit()
item_list = session.query(Student.name, Student.age).all()
print(item_list)
執行結果如下
[('Tony', 22), ('Jane', 16)]