SqlAlchemy ORM
SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果
Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:
1 MySQL-Python 2 mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname> 3 4 pymysql 5 mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>] 6 7 MySQL-Connector 8 mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname> 9 10 cx_Oracle 11 oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...] 12 13 更多详见:http://docs.sqlalchemy.org/en/latest/dialects/index.html
步骤一:
使用 Engine/ConnectionPooling/Dialect 进行数据库操作,Engine使用ConnectionPooling连接数据库,然后再通过Dialect执行SQL语句。
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 from sqlalchemy import create_engine 5 6 7 engine = create_engine("mysql+mysqldb://root:[email protected]:3306/s11", max_overflow=5) 8 9 engine.execute( 10 "INSERT INTO ts_test (a, b) VALUES (‘2‘, ‘v1‘)" 11 ) 12 13 engine.execute( 14 "INSERT INTO ts_test (a, b) VALUES (%s, %s)", 15 ((555, "v1"),(666, "v1"),) 16 ) 17 engine.execute( 18 "INSERT INTO ts_test (a, b) VALUES (%(id)s, %(name)s)", 19 id=999, name="v1" 20 ) 21 22 result = engine.execute(‘select * from ts_test‘) 23 result.fetchall()
步骤二:
使用 Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 进行数据库操作。Engine使用Schema Type创建一个特定的结构对象,之后通过SQL Expression Language将该对象转换成SQL语句,然后通过 ConnectionPooling 连接数据库,再然后通过 Dialect 执行SQL,并获取结果。
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey 5 6 metadata = MetaData() 7 8 user = Table(‘user‘, metadata, 9 Column(‘id‘, Integer, primary_key=True), 10 Column(‘name‘, String(20)), 11 ) 12 13 color = Table(‘color‘, metadata, 14 Column(‘id‘, Integer, primary_key=True), 15 Column(‘name‘, String(20)), 16 ) 17 engine = create_engine("mysql+mysqldb://[email protected]:3306/test", max_overflow=5) 18 19 metadata.create_all(engine)
增删改查
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey 5 6 metadata = MetaData() 7 8 user = Table(‘user‘, metadata, 9 Column(‘id‘, Integer, primary_key=True), 10 Column(‘name‘, String(20)), 11 ) 12 13 color = Table(‘color‘, metadata, 14 Column(‘id‘, Integer, primary_key=True), 15 Column(‘name‘, String(20)), 16 ) 17 engine = create_engine("mysql+mysqldb://root:[email protected]:3306/s11", max_overflow=5) 18 19 conn = engine.connect() 20 21 # 创建SQL语句,INSERT INTO "user" (id, name) VALUES (:id, :name) 22 conn.execute(user.insert(),{‘id‘:7,‘name‘:‘seven‘}) 23 conn.close() 24 25 # sql = user.insert().values(id=123, name=‘wu‘) 26 # conn.execute(sql) 27 # conn.close() 28 29 # sql = user.delete().where(user.c.id > 1) 30 31 # sql = user.update().values(fullname=user.c.name) 32 # sql = user.update().where(user.c.name == ‘jack‘).values(name=‘ed‘) 33 34 # sql = select([user, ]) 35 # sql = select([user.c.id, ]) 36 # sql = select([user.c.name, color.c.name]).where(user.c.id==color.c.id) 37 # sql = select([user.c.name]).order_by(user.c.name) 38 # sql = select([user]).group_by(user.c.name) 39 40 # result = conn.execute(sql) 41 # print result.fetchall() 42 # conn.close()
Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
步骤一:
使用 Engine/ConnectionPooling/Dialect 进行数据库操作,Engine使用ConnectionPooling连接数据库,然后再通过Dialect执行SQL语句。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
步骤二:
使用 Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 进行数据库操作。Engine使用Schema Type创建一个特定的结构对象,之后通过SQL Expression Language将该对象转换成SQL语句,然后通过 ConnectionPooling 连接数据库,再然后通过 Dialect 执行SQL,并获取结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
增删改查
一个简单的完整例子
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 |
|
更多内容详见:
http://www.jianshu.com/p/e6bba189fcbd
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 |
|
外键关联
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 |
|
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 |
|
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 |
|
附,原生sql join查询
几个Join的区别 http://stackoverflow.com/questions/38549/difference-between-inner-and-outer-joins
- INNER JOIN: Returns all rows when there is at least one match in BOTH tables
- LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
- RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
1 |
|
in SQLAchemy
1 |
|
group by 查询
1 |
|
in SQLAchemy
1 2 3 4 5 6 |
|
分类: Python之路
好文要顶 关注我 收藏该文
0
0
(请您对文章做出评价)
posted @ 2016-03-06 19:14 金角大王 阅读(937) 评论(0) 编辑 收藏