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 until session.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 what session.commit() does).
  • session.commit() commits (persists) those changes to the database.
  • flush() is always called as part of a call to commit()

定义映射

>>> 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的更多相关文章

  1. SQLAlchemy指南(tutorial)

    对应版本: 0.3.4 目录 1 安装 1.1 安装SQLAlchemy 1.2 安装一个数据库API 2 快速开始 2.1 导入 2.2 连接到数据库 3 SQLAlchemy是两个库的包装 4 操 ...

  2. 使用SQLAlchemy

    使用SQLAlchemy 参考: http://www.sqlalchemy.org/ https://www.keakon.net/2012/12/03/SQLAlchemy%E4%BD%BF%E7 ...

  3. 3.SQLAlchemy文档-SQLAlchemy Core(中文版)

    这里的文描述了关于SQLAlchemy的的SQL渲染引擎的相关内容,包括数据库API的集成,事务的集成和数据架构描述服务.与以领域为中心的ORM使用模式相反,SQL表达式语言提供了一个数据构架为中心的 ...

  4. (翻译玩)SQLALchemy backref章节文档

    Linking Relationships with Backref 自从在Object Relational Tutorial中第一次提到backref参数后,许多案例中也用到了backref,那么 ...

  5. SQLAlchemy on the way

    SQLAlchemy Trial This is a great ORM ( Object-Relational Mapper ) which is compatible with  xxxx and ...

  6. Object Relational Tutorial 对象关系教程

    The SQLAlchemy Object Relational Mapper presents a method of associating user-defined Python classes ...

  7. 好用的SQLAlchemy

    准备 安装SQLAlchemy框架 测试代码 知识点剖析 引入库支持 基类和引擎 实体类 声明类 数据库自动完成 CRUD 总结 这里简单的记录一下本人第一次使用SQLAlchemy这个ORM框架的过 ...

  8. Python3+SQLAlchemy+Sqlite3实现ORM教程

    一.安装 Sqlite3是Python3标准库不需要另外安装,只需要安装SQLAlchemy即可.本文sqlalchemy版本为1.2.12 pip install sqlalchemy 二.ORM操 ...

  9. Flask使用SQLAlchemy两种方式

    一.SQLAlchemy和Alembic 主要使用原生的SQLAlchemy进行数据库操作和使用Alemic进行数据库版本控制 I 创建数据库主要有三个步骤 创建表的父类/数据库连接/Session ...

随机推荐

  1. 超酷消息警告框插件(SweetAlert)

    今天给大家推荐一款不错的超酷消息警告框–SweetAlert:SweetAlert是一款不需要jQuery支持的原生js提示框,风格类似bootstrap.它的提示框不仅美丽动人,并且允许自定义,支持 ...

  2. day06-08初识面向对象

    一.面向过程 VS 面向对象 面向过程的程序设计的核心是过程(流水线式思维),过程即解决问题的步骤,面向过程的设计就好比精心设计好一条流水线,考虑周全什么时候处理什么东西.优点是:极大的降低了写程序的 ...

  3. Java范式1

    package Xwxx; public class Person { private String name; private int age; public Person() { } public ...

  4. HDU2516 - 取石子游戏【斐波那契博弈】

    基本描述 有一堆个数为n的石子,游戏双方轮流取石子,满足: 先手不能再第一次把所有石子取完: 之后每次可以取的石子数介于1到对手刚取的石子数的2倍之间,包括1和对手取的石子数的2倍.  取最后石子的人 ...

  5. [SCOI2010] 股票交易 (单调队列优化dp)

    题目描述 最近lxhgww又迷上了投资股票,通过一段时间的观察和学习,他总结出了股票行情的一些规律. 通过一段时间的观察,lxhgww预测到了未来T天内某只股票的走势,第i天的股票买入价为每股APi, ...

  6. django模板使用

    概述 模板由两部分组成,HTML代码,逻辑控制代码,作用:快速生成HTML页面,优点:模板的设计实现了业务逻辑与现实内容的分离 定义模板 挖坑与继承 模板继承可以减少页面的内容的重复定义,实现页面的重 ...

  7. ssh远程连接和linux基本操作

    客户端工具:Xshell,SecureCRT 启动网卡(eth0): ifup eth0 查看IP地址: ifconfig       [root@oldboy~] : [登入名 @ 主机名 文件或者 ...

  8. 【CodeForces 987C】Three displays

    [链接] 我是链接,点我呀:) [题意] [题解] 动态规划 设dp[i][j]表示前i个数字,选了j个的最小花费. dp[i][j] = min(dp[k][j-1]+b[i]);//其中a[i]& ...

  9. WebStorm 6.0 与 7.0 注册码

    经测试 WebStorm 7均可以使用如下注册码,简直就是神key啊! WebStorm 6.0 与 7.0 注册码 User Name: EMBRACE License Key: ===== LIC ...

  10. BA-通讯总线-百通1419a和9841

    百通1419A线缆的简单介绍: Belden1419A- Belden电缆线1419A 多股导体—低容计算机电缆 FOR EIA RS-232/422 Belden 1419A是24 AWG(7*32 ...