SQLAlchemy是Python编程语言下的一款开源软件,提供了SQL工具包及对象关系映射(ORM)工具,使用MIT许可证发行。SQLAlchemy采用简单的Python语言,为高效和高性能的数据库访问设计,实现了完整的企业级持久模型。
本文将对sqlalchemy的基本使用进行介绍。
Demo准备
依赖配置
在requriments.txt中配置依赖:
MySQL-python==1.2.5
SQLAlchemy==1.2.15
在src目录下创建settings文件,读取配置信息:
import ConfigParser
import os
import argparse
parser = argparse.ArgumentParser(description='Start servers.')
configuration = ConfigParser.ConfigParser()
# 从命令行读取参数,无config参数时取默认值config
parser.add_argument('-c', '--config', dest='config', default='config', help='specify the location of the config file')
parser.add_argument('-a', '--arg', dest='arg', help='other args.')
args = parser.parse_args()
# 当config参数合法时,读取配置文件参数,并将命令行arg参数添加到main中.
# 可通过settings.args.arg或settings.get('main', 'arg')取出
if os.path.exists(args.config):
configuration.read(args.config)
if args.arg:
configuration.set('main', 'arg', value=args.arg)
else:
parser.print_help()
def getint(section, option):
return configuration.getint(section, option)
def get(section, option):
return configuration.get(section, option)
def getboolean(section, option):
return configuration.getboolean(section, option)
def getfloat(section, option):
return configuration.getfloat(section, option)
def set(section, option, value=None):
return configuration.set(section, option, value=value)
config(无文件后缀)如下(echo为True表示打开logging):
[main]
debug = true
[mysql]
host = mysql://[user]:[password]@[host]:[port]/[dbname]?charset=utf8
charset = utf-8
echo = false
创建mysql_base.py,用于连接数据库:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import settings
Base = declarative_base()
mysql_engine = create_engine(
settings.get('mysql', 'host'),
echo=settings.getboolean('mysql', 'echo'),
encoding=settings.get('mysql', 'charset')
)
Session = sessionmaker(bind=mysql_engine)
session = Session()
session.execute('show databases')
创建一个orm映射, 一个映射对应一个Python类,用来表示一个表的结构。 下面创建一个Person表,包括id和name两个字段:
from base.mysql_base import Base, session
from sqlalchemy import *
class Person(Base):
__tablename__ = 'person'
id = Column(BigInteger, primary_key=True, autoincrement=True)
name = Column(String(64), nullable=False)
创建一个Address表,包括id,name和person_id字段:
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String, nullable=False)
person_id = Column(Integer, nullable=False)
CURD操作
# 新增单条数据
session.add(Person(name=’jack’))
# 新增多条数据
session.add_all([Person(name=’mike’), Person(name=’siri’)])
session.commit()
session.query(Person).limit(100).all()
# 按条件查询
session.query(Person).filter(Person.name == ‘jack’).all()
# 查询第一条
session.query(Person).first()
# 过滤和limit
session.query(Person.name).filter(Person.id > 1).all()[1:3]
# 排序
session.query(Person).order_by(-Person.id).limit(10).all()
session.query(Person).order_by(desc(Person.id)).limit(10).all()
# 模糊查询
query = session.query(Person)
query.filter(Person.name.like(‘%ac%’)).all()
query.filter(Person.id.in_([1, 2, 3])).all()
# and or
query.filter(Person(Person.id == 1, Person.name == ‘jack’)).all()
query.filter(and_(Person.id == 1, Person.name == ‘jack’)).all()
query.filter(Person.id == 1).filter(Person.name == ‘jack’).all()
query.filter(or_(Person.id == 1, Person.id == 2)).all()
# 使用text自定义sql
query.filter(text(“id”> 1)).all()
query.filter(text(“id > :id”)).params(id = 1).all()
query.from_statement(text(“select * from person where name = :name”)).params(name= ‘jack’).all()
# count 和 group
query.filter(Person.id > 1).count()
session.query(func.count(Person.id)).scalar()
session.query(func.count(‘*’)).select_from(Person).scalar()
session.query(func.count(Person.name), Person.name).group_by(Person.name).all()
# 连表查询和统计
sql_from = Person.__table__.join(Address.__table__, Person.id == Address.person_id)
sql = select([func.count()]).select_from(sql_from).where(Person.name == 'jack')
count = session.execute(sql).scalar()
docs = session.query(Person.id, Person.name, Address.name).select_from(sql_from).filter(Person.name == 'jack').all()