SQLAlchemy tutorial
SQLAlchemy tutorial
重要概念
- ORM:数据库对象 <--> class --> 类实例instance
- 定义数据库连接
- session:数据库事务通过session操作,flush()提交到内存但是未提交到数据库,commit()保存到数据库;
commit()
flushes whatever remaining changes remain to the database, and commits the transaction. The connection resources referenced by the session are now returned to the connection pool. Subsequent operations with this session will occur in a new transaction, which will again re-acquire connection resources when first needed.
或者 What's the difference between flush() and commit()
- The session object registers transaction operations with
session.add()
, but doesn't yet communicate them to the database untilsession.flush()
is called.session.flush()
communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction. The changes aren't persisted permanently to disk, or visible to other transactions until the database receives a COMMIT for the current transaction (which is whatsession.commit()
does).session.commit()
commits (persists) those changes to the database.flush()
is always called as part of a call tocommit()
定义映射
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite:///:memory:', echo=True)
>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarative_base()
>>> from sqlalchemy import Column, Integer, String
>>> class User(Base):
... __tablename__ = 'users'
... id = Column(Integer, primary_key=True)
... name = Column(String(50))
... fullname = Column(String(50))
... password = Column(String(12))
... def __repr__(self):
... return "<User(name='%s', fullname='%s', password='%s')>" % (self.nam
e, self.fullname, self.password)
...
class 定义
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
fullname = Column(String(50))
password = Column(String(12))
def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (self.name, self.fullname, self.password)
创建数据库
>>> Base.metadata.create_all(engine)
2015-12-29 15:56:59,029 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2015-12-29 15:56:59,030 INFO sqlalchemy.engine.base.Engine ()
2015-12-29 15:56:59,035 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2015-12-29 15:56:59,036 INFO sqlalchemy.engine.base.Engine ()
2015-12-29 15:56:59,039 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("users")
2015-12-29 15:56:59,039 INFO sqlalchemy.engine.base.Engine ()
2015-12-29 15:56:59,042 INFO sqlalchemy.engine.base.Engine
CREATE TABLE users (
id INTEGER NOT NULL,
name VARCHAR(50),
fullname VARCHAR(50),
password VARCHAR(12),
PRIMARY KEY (id)
)
2015-12-29 15:56:59,043 INFO sqlalchemy.engine.base.Engine ()
2015-12-29 15:56:59,046 INFO sqlalchemy.engine.base.Engine COMMIT
添加数据
>>> ed_user = User(name='ed', fullname='Ed Jones', password='edspassword')
>>> str(ed_user.id)
'None'
>>> from sqlalchemy.orm import sessionmaker
>>> Session = sessionmaker(bind=engine)
>>> session = Session()
>>> session.add(ed_user)
>>> our_user = session.query(User).filter_by(name='ed').first()
2015-12-29 15:57:48,361 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2015-12-29 15:57:48,364 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
2015-12-29 15:57:48,365 INFO sqlalchemy.engine.base.Engine ('ed', 'Ed Jones', 'edspassword')
2015-12-29 15:57:48,369 INFO sqlalchemy.engine.base.Engine
SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password
FROM users
WHERE users.name = ?
LIMIT ? OFFSET ?
2015-12-29 15:57:48,371 INFO sqlalchemy.engine.base.Engine ('ed', 1, 0)
>>> our_user
<User(name='ed', fullname='Ed Jones', password='edspassword')>
>>> ed_user is our_user
True
>>> session.add_all([
... User(name='wendy', fullname='Wendy Williams', password='foobar'),
... User(name='mary', fullname='Mary Contrary', password='xxg527'),
... User(name='fred', fullname='Fred Flinstone', password='blah')])
>>> ed_user.password = 'f8s7ccs'
>>> session.dirty
IdentitySet([<User(name='ed', fullname='Ed Jones', password='f8s7ccs')>])
>>> session.new
IdentitySet([<User(name='wendy', fullname='Wendy Williams', password='foobar')>,
<User(name='fred', fullname='Fred Flinstone', password='blah')>, <User(name='ma
ry', fullname='Mary Contrary', password='xxg527')>])
>>> session.commit()
2015-12-29 16:05:12,272 INFO sqlalchemy.engine.base.Engine UPDATE users SET password=? WHERE users.id = ?
2015-12-29 16:05:12,273 INFO sqlalchemy.engine.base.Engine ('f8s7ccs', 1)
2015-12-29 16:05:12,275 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
2015-12-29 16:05:12,276 INFO sqlalchemy.engine.base.Engine ('wendy', 'Wendy Williams', 'foobar')
2015-12-29 16:05:12,278 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
2015-12-29 16:05:12,279 INFO sqlalchemy.engine.base.Engine ('mary', 'Mary Contrary', 'xxg527')
2015-12-29 16:05:12,280 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
2015-12-29 16:05:12,282 INFO sqlalchemy.engine.base.Engine ('fred', 'Fred Flinstone', 'blah')
2015-12-29 16:05:12,285 INFO sqlalchemy.engine.base.Engine COMMIT
>>> ed_user.id
2015-12-29 16:06:27,977 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2015-12-29 16:06:27,980 INFO sqlalchemy.engine.base.Engine SELECT users.id AS us
ers_id, users.name AS users_name, users.fullname AS users_fullname, users.passwo
rd AS users_password
FROM users
WHERE users.id = ?
2015-12-29 16:06:27,983 INFO sqlalchemy.engine.base.Engine (1,)
1
>>> ed_user.id
1
事务回滚 Rolling Back
>>> ed_user.name = 'Edwardo'
>>> fake_user = User(name='fakeuser', fullname='Invalid', password='12345')
>>> session.add(fake_user)
>>> session.query(User).filter(User.name.in_(['Edwardo', 'fakeuser'])).all()
2015-12-29 16:10:52,517 INFO sqlalchemy.engine.base.Engine UPDATE users SET name=? WHERE users.id = ?
2015-12-29 16:10:52,519 INFO sqlalchemy.engine.base.Engine ('Edwardo', 1)
2015-12-29 16:10:52,520 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
2015-12-29 16:10:52,522 INFO sqlalchemy.engine.base.Engine ('fakeuser', 'Invalid', '12345')
2015-12-29 16:10:52,528 INFO sqlalchemy.engine.base.Engine
SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password
FROM users
WHERE users.name IN (?, ?)
2015-12-29 16:10:52,529 INFO sqlalchemy.engine.base.Engine ('Edwardo', 'fakeuser')
[<User(name='Edwardo', fullname='Ed Jones', password='f8s7ccs')>, <User(name='fa
keuser', fullname='Invalid', password='12345')>]
>>> session.rollback()
2015-12-29 16:11:14,276 INFO sqlalchemy.engine.base.Engine ROLLBACK
>>> ed_user.name
2015-12-29 16:11:20,378 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2015-12-29 16:11:20,381 INFO sqlalchemy.engine.base.Engine
SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password
FROM users
WHERE users.id = ?
2015-12-29 16:11:20,384 INFO sqlalchemy.engine.base.Engine (1,)
u'ed'
>>> fake_user in session
False
>>> session.query(User).filter(User.name.in_(['ed', 'fakeuser'])).all()
2015-12-29 16:11:35,526 INFO sqlalchemy.engine.base.Engine
SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password
FROM users
WHERE users.name IN (?, ?)
2015-12-29 16:11:35,529 INFO sqlalchemy.engine.base.Engine ('ed', 'fakeuser')
[<User(name='ed', fullname='Ed Jones', password='f8s7ccs')>]
SQLAlchemy tutorial的更多相关文章
- SQLAlchemy指南(tutorial)
对应版本: 0.3.4 目录 1 安装 1.1 安装SQLAlchemy 1.2 安装一个数据库API 2 快速开始 2.1 导入 2.2 连接到数据库 3 SQLAlchemy是两个库的包装 4 操 ...
- 使用SQLAlchemy
使用SQLAlchemy 参考: http://www.sqlalchemy.org/ https://www.keakon.net/2012/12/03/SQLAlchemy%E4%BD%BF%E7 ...
- 3.SQLAlchemy文档-SQLAlchemy Core(中文版)
这里的文描述了关于SQLAlchemy的的SQL渲染引擎的相关内容,包括数据库API的集成,事务的集成和数据架构描述服务.与以领域为中心的ORM使用模式相反,SQL表达式语言提供了一个数据构架为中心的 ...
- (翻译玩)SQLALchemy backref章节文档
Linking Relationships with Backref 自从在Object Relational Tutorial中第一次提到backref参数后,许多案例中也用到了backref,那么 ...
- SQLAlchemy on the way
SQLAlchemy Trial This is a great ORM ( Object-Relational Mapper ) which is compatible with xxxx and ...
- Object Relational Tutorial 对象关系教程
The SQLAlchemy Object Relational Mapper presents a method of associating user-defined Python classes ...
- 好用的SQLAlchemy
准备 安装SQLAlchemy框架 测试代码 知识点剖析 引入库支持 基类和引擎 实体类 声明类 数据库自动完成 CRUD 总结 这里简单的记录一下本人第一次使用SQLAlchemy这个ORM框架的过 ...
- Python3+SQLAlchemy+Sqlite3实现ORM教程
一.安装 Sqlite3是Python3标准库不需要另外安装,只需要安装SQLAlchemy即可.本文sqlalchemy版本为1.2.12 pip install sqlalchemy 二.ORM操 ...
- Flask使用SQLAlchemy两种方式
一.SQLAlchemy和Alembic 主要使用原生的SQLAlchemy进行数据库操作和使用Alemic进行数据库版本控制 I 创建数据库主要有三个步骤 创建表的父类/数据库连接/Session ...
随机推荐
- UVa340未完成
#include<stdio.h> #define maxn 1010 int main() { ; while(scanf("%d",&num)!=EOF&a ...
- css3的过滤效果
上面的图片就是css3新特性的滤镜效果,学会了这些那么我们这群爱美爱帅的大web是不是就可以完美的用代码实现照片美化了捏~~ 好,咱们先把照片后面的白框实现, <style> #div1{ ...
- What are lazy variables?
Written by Paul Hudson @twostraws It's very common in iOS to want to create complex objects only ...
- JS 封装一个显示时间的函数
s(); function s (){ var mydate=new Date(); var y = mydate.getFullYear(); var m = mydate.getMonth(); ...
- 洛谷P2827 蚯蚓 队列 + 观察
我们不难发现先被切开的两半一定比后被切开的两半大,这样就天然的生成了队列的单调性,就可以省去一个log.所以,我们开三个队列,分别为origin,big,smallorigin, big, small ...
- 【udacity】机器学习-决策树
Evernote Export 1.监督学习 我们向系统中输出样本,并且告诉系统样本标签(target),系统用我们给出的不同样本的成功与失败的信息,构建它对成功或失败的因素的理解. 2.分类与回归之 ...
- [LUOGU2730] 魔板
搜索水题.因为只有8个数,排列一共有40320种,直接bfs,判重就行了. 但是判重的时候直接用8进制表示的话要88的bool数组.这种操作太low了,于是我们可以用康托展开,降成8!. 康托展开其实 ...
- 【Manthan, Codefest 18 (rated, Div. 1 + Div. 2) B】Reach Median
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 将数组排序一下. 考虑中位数a[mid] 如果a[mid]==s直接输出0 如果a[mid]<s,那么我们把a[mid]改成s ...
- TensorFlow 版本问题
TensorFlow各个版本均可以在GitHub上下载,之前下载配置的是0.5.0版本,运行的时候,出现很多问题,什么模块缺失attribute,函数参数问题等,修改起来让人抓狂,后来索性下载使用0. ...
- 计算机网络系统--TCP/IP OSI模型