简介
SQLalchemy 是 Python 中最著名的 ORM(Object Relationship Mapping) 框架
https://github.com/sqlalchemy/sqlalchemy
https://github.com/sqlalchemy
https://www.sqlalchemy.org/
英文文档
中文文档
连接数据库(创建引擎)
以 SQLite 为例, 连接数据库的URL形式: sqlite:///
+ 文件路径
1
2
3
4
5
6
7
8
9
10
11
12
13 | In [3]: from sqlalchemy import create_engine
In [10]: engine = create_engine('sqlite:///test.db', echo=True)
In [11]: engine.execute('create table user (id int(10) primary key, name varchar(20))')
2019-09-09 21:35:28,190 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2019-09-09 21:35:28,191 INFO sqlalchemy.engine.base.Engine ()
2019-09-09 21:35:28,191 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2019-09-09 21:35:28,191 INFO sqlalchemy.engine.base.Engine ()
2019-09-09 21:35:28,192 INFO sqlalchemy.engine.base.Engine create table user (id int(10) primary key, name varchar(20))
2019-09-09 21:35:28,192 INFO sqlalchemy.engine.base.Engine ()
2019-09-09 21:35:28,194 INFO sqlalchemy.engine.base.Engine COMMIT
Out[11]: <sqlalchemy.engine.result.ResultProxy at 0x107614278>
|
echo
参数是用来设置 SQLAlchemy 日志的,通过 Python 标准库logging
模块实现。设置为True
的时候我们可以看见所以的操作记录
初次调用create_engine()
的时候并不会真正的去连接数据库,只有在真正执行一条命令的时候才会去尝试建立连接, 目的是节省资源
当第一次调用 Engine.execute()
或者 Engine.connect()
这种方法的时候,引擎(Engine)会和数据库建立一个真正的 DBAPI 连接,用来执行 SQL 语句。
但是在创建了连接之后,我们很少直接使用 Engine 来操作数据库
连接其他数据库
The string form of the URL is dialect[+driver]://user:password@host/dbname[?key=value..]
,
where dialect
is a database name such as mysql
, oracle
,postgresql
, etc.,
and driver
the name of a DBAPI, such as psycopg2
, pyodbc
, cx_oracle
, etc.
| engine = create_engine("postgresql://scott:tiger@localhost/test")
engine = create_engine("mysql://scott:tiger@hostname/dbname", encoding='latin1', echo=True)
|
创建基类
| from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
|
创建模型对象
| from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String
Base = declarative_base()
class User(Base):
# 表的名字
__tablename__ = 'user'
# 表的结构
id = Column(String(20), primary_key=True)
name = Column(String(20))
|
利用SQLAlchemy中的Session对象进行一些高级数据操作,
包括distinct、limit、offset、scalar、count、average、sum、filter、group by、order by等。