SQLAlchemy是Python編程語言下的一款ORM框架,該框架創建在數據庫API之上,使用關係對象映射進行數據庫操做,簡言之即是:將對象轉換成SQL,而後使用數據API執行SQL並獲取執行結果html
Dialect用於和數據API進行交流,根據配置文件的不一樣調用不一樣的數據庫API,從而實現對數據庫的操做,如:python
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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
|
步驟一:mysql
使用 Engine/ConnectionPooling/Dialect 進行數據庫操做,Engine使用ConnectionPooling鏈接數據庫,而後再經過Dialect執行SQL語句。sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from
sqlalchemy
import
create_engine
engine.execute(
"INSERT INTO ts_test (a, b) VALUES ('2', 'v1')"
)
engine.execute(
"INSERT INTO ts_test (a, b) VALUES (%s, %s)"
,
((
555
,
"v1"
),(
666
,
"v1"
),)
)
engine.execute(
"INSERT INTO ts_test (a, b) VALUES (%(id)s, %(name)s)"
,
id
=
999
, name
=
"v1"
)
result
=
engine.execute(
'select * from ts_test'
)
result.fetchall()
|
步驟二:數據庫
使用 Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 進行數據庫操做。Engine使用Schema Type建立一個特定的結構對象,以後經過SQL Expression Language將該對象轉換成SQL語句,而後經過 ConnectionPooling 鏈接數據庫,再而後經過 Dialect 執行SQL,並獲取結果。express
增刪改查編程
一個簡單的完整例子ubuntu
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
|
from
sqlalchemy
import
create_engine
from
sqlalchemy.ext.declarative
import
declarative_base
from
sqlalchemy
import
Column, Integer, String
from
sqlalchemy.orm
import
sessionmaker
Base
=
declarative_base()
#生成一個SqlORM 基類
class
Host(Base):
__tablename__
=
'hosts'
id
=
Column(Integer,primary_key
=
True
,autoincrement
=
True
)
hostname
=
Column(String(
64
),unique
=
True
,nullable
=
False
)
ip_addr
=
Column(String(
128
),unique
=
True
,nullable
=
False
)
port
=
Column(Integer,default
=
22
)
Base.metadata.create_all(engine)
#建立全部表結構
if
__name__
=
=
'__main__'
:
SessionCls
=
sessionmaker(bind
=
engine)
#建立與數據庫的會話session class ,注意,這裏返回給session的是個class,不是實例
session
=
SessionCls()
#h1 = Host(hostname='localhost',ip_addr='127.0.0.1')
#h2 = Host(hostname='ubuntu',ip_addr='192.168.2.243',port=20000)
#h3 = Host(hostname='ubuntu2',ip_addr='192.168.2.244',port=20000)
#session.add(h3)
#session.add_all( [h1,h2])
#h2.hostname = 'ubuntu_test' #只要沒提交,此時修改也沒問題
#session.rollback()
#session.commit() #提交
res
=
session.query(Host).
filter
(Host.hostname.in_([
'ubuntu2'
,
'localhost'
])).
all
()
print
(res)
|
更多內容詳見:api
http://www.jianshu.com/p/e6bba189fcbdsession
http://docs.sqlalchemy.org/en/latest/core/expression_api.html
注:SQLAlchemy沒法修改表結構,若是須要能夠使用SQLAlchemy開發者開源的另一個軟件Alembic來完成。
步驟三:
使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 全部組件對數據進行操做。根據類建立對象,對象轉換成SQL,執行SQL。
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
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from
sqlalchemy.ext.declarative
import
declarative_base
from
sqlalchemy
import
Column, Integer, String
from
sqlalchemy.orm
import
sessionmaker
from
sqlalchemy
import
create_engine
Base
=
declarative_base()
class
User(Base):
__tablename__
=
'users'
id
=
Column(Integer, primary_key
=
True
)
name
=
Column(String(
50
))
# 尋找Base的全部子類,按照子類的結構在數據庫中生成對應的數據表信息
# Base.metadata.create_all(engine)
Session
=
sessionmaker(bind
=
engine)
session
=
Session()
# ########## 增 ##########
# u = User(id=2, name='sb')
# session.add(u)
# session.add_all([
# User(id=3, name='sb'),
# User(id=4, name='sb')
# ])
# session.commit()
# ########## 刪除 ##########
# session.query(User).filter(User.id > 2).delete()
# session.commit()
# ########## 修改 ##########
# session.query(User).filter(User.id > 2).update({'cluster_id' : 0})
# session.commit()
# ########## 查 ##########
# ret = session.query(User).filter_by(name='sb').first()
# ret = session.query(User).filter_by(name='sb').all()
# print ret
# ret = session.query(User).filter(User.name.in_(['sb','bb'])).all()
# print ret
# ret = session.query(User.name.label('name_label')).all()
# print ret,type(ret)
# ret = session.query(User).order_by(User.id).all()
# print ret
# ret = session.query(User).order_by(User.id)[1:3]
# print ret
# session.commit()
|
A one to many relationship places a foreign key on the child table referencing the parent.relationship()
is then specified on the parent, as referencing a collection of items represented by the child
from sqlalchemy import Table, Column, Integer, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base()
1
2
3
4
5
6
7
8
9
|
<br>
class
Parent(Base):
__tablename__
=
'parent'
id
=
Column(Integer, primary_key
=
True
)
children
=
relationship(
"Child"
)
class
Child(Base):
__tablename__
=
'child'
id
=
Column(Integer, primary_key
=
True
)
parent_id
=
Column(Integer, ForeignKey(
'parent.id'
))
|
To establish a bidirectional relationship in one-to-many, where the 「reverse」 side is a many to one, specify an additional relationship()
and connect the two using therelationship.back_populates
parameter:
1
2
3
4
5
6
7
8
9
10
|
class
Parent(Base):
__tablename__
=
'parent'
id
=
Column(Integer, primary_key
=
True
)
children
=
relationship(
"Child"
, back_populates
=
"parent"
)
class
Child(Base):
__tablename__
=
'child'
id
=
Column(Integer, primary_key
=
True
)
parent_id
=
Column(Integer, ForeignKey(
'parent.id'
))
parent
=
relationship(
"Parent"
, back_populates
=
"children"
)
|
Child
will get a parent
attribute with many-to-one semantics.
Alternatively, the backref
option may be used on a single relationship()
instead of usingback_populates
:
1
2
3
4
|
class
Parent(Base):
__tablename__
=
'parent'
id
=
Column(Integer, primary_key
=
True
)
children
=
relationship(
"Child"
, backref
=
"parent"
)
|
附,原生sql join查詢
幾個Join的區別 http://stackoverflow.com/questions/38549/difference-between-inner-and-outer-joins
1
|
select
host.id,hostname,ip_addr,port,host_group.
name
from
host
right
join
host_group
on
host.id = host_group.host_id
|
in SQLAchemy
1
|
session.query(Host).
join
(Host.host_groups).filter(HostGroup.
name
==
't1'
).group_by(
"Host"
).
all
()
|
group by 查詢
1
|
select
name
,
count
(host.id)
as
NumberOfHosts
from
host
right
join
host_group
on
host.id= host_group.host_id
group
by
name
;
|
in SQLAchemy
1
2
3
4
5
6
|
from
sqlalchemy import func
session.query(HostGroup, func.
count
(HostGroup.
name
)).group_by(HostGroup.
name
).
all
()
#another example
session.query(func.
count
(
User
.
name
),
User
.
name
).group_by(
User
.
name
).
all
()
SELECT
count
(users.
name
)
AS
count_1, users.
name
AS
users_name
FROM
users
GROUP
BY
users.
name
|