# 生成模板

pip install sqlacodegen

pip install pymysql

sqlacodegen mysql+pymysql://username:password@127.0.0.1:3306/db_name > models_tmp.py
1
2
3
4
5

# 操作实例

data = session.query(Emp).from_statement(text('select * from emp where id=2')).params(name='123').all()
1

# 生成单表

sqlacodegen --tables third_api "mysql+pymysql://username:password@host/db_name" >tmp.py
1

# 基础查询

等于查询:

query.filter(User.name == 'ed')

不等于查询:

query.filter(User.name != 'ed')

like查询:

query.filter(User.name.like('%ed%'))

in查询:

query.filter(User.name.in_(['ed', 'wendy', 'jack']))

not in 查询

query.filter(~User.name.in_(['ed', 'wendy', 'jack']))

is null查询:

query.filter(User.name == None)

is not null查询

query.filter(User.name != None)

and查询:

from sqlalchemy import and_

query.filter(and_(User.name == 'ed', User.fullname == 'Ed Jones'))

# or send multiple expressions to .filter()
query.filter(User.name == 'ed', User.fullname == 'Ed Jones')


or查询:

from sqlalchemy import or_
query.filter(or_(User.name == 'ed', User.name == 'wendy'))

match查询

query.filter(User.name.match('wendy'))

order_by语句:

query = session.query(User).filter(User.name.like('%ed')).order_by(User.id)

count计数

session.query(User).filter(User.name.like('%ed')).count()

分页查询

session.query(Channel).filter(and_(
                filter_list
            )).order_by(desc(Channel.updateTime)).slice(offset, limit)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60