orm 数据状态的预知识

瞬时状态:刚创建的对象还没有被Session持久化、缓存中不存在这个对象的数据并且数据库中没有这个对象对应的数据为瞬时状态这个时候是没有OID。   

持久状态:对象经过Session持久化操作,缓存中存在这个对象的数据为持久状态并且数据库中存在这个对象对应的数据为持久状态这个时候有OID。
游离状态:当Session关闭,缓存中不存在这个对象数据而数据库中有这个对象的数据并且有OID为游离状态。

数据实例对象有四种状态,分别是
Transient - (瞬时的)
表示该实例对象不在session中,当然也没有保存到数据库中,
主键一般情况下为None(如果一个Persistent状态的对象进行事务回滚后虽然主键有值,但却是Transient状态)。

Pending - (挂起的)
调用session.add()后,Transient状态的对象就会变成Pending状态的对象,这个时候它只是在session中,
并没有保存到数据库,因此主键依旧为None。
只有触发了session.flush()操作才会保存到数据库使得主键有值,比如查询操作就会触发flush。

Persistent - (持久的)
session和数据库中都有对应的记录存在,为持久状态。

Detached - (游离的)
数据库中可能有记录,但是session中不存在。对这种对象的操作不会触发任何SQL语句。

文档 http://docs.sqlalchemy.org/en/latest/
#------------- connect db two kinds or many , and finally it tests for pass for every platform!
#------------- mapping bean to db.table
#------------- orm crud
#------------- sql operation and compex sql

#------------- connect db two kinds or many , and finally it can pass for every platform!
def connectDBgetSesion():
engine = create_engine('sqlite:///db.sqlite3', echo=True) # echo=False 为不显示sql
# engine = create_engine("mysql+pymysql://root:12456@localhost:3306/tessql?charset=utf8", echo=True)

Session = sessionmaker(bind=engine)
session = Session()
return session
def close(session):
session.commit()
session.close()
#------------- mapping bean to db.table
engine = create_engine('sqlite:///../db.sqlite3', echo=True)
# engine = create_engine("mysql+pymysql://root:123456@localhost:3306/testpymysql?charset=utf8", echo=True)
Base = declarative_base()

class User(Base):
__tablename__ = 'users'
# id = Column(Integer, primary_key=True)
id = Column(Integer, Sequence('user_id_seq'), 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)

#------------- orm crud
#-------------c
try:
session = connectDBgetSesion()
# "INSERT INTO custom__desc ( ,word_desc) VALUES (%s,%s) "
custom_ _desc = Custom_ _desc( =new word,word_desc=newperfword)
session.add(custom_ _desc)
except Exception as e:
print(e)
finally:
close(session)
#-------------r
# sql = "SELECT DISTINCT word_desc FROM t"
all_custom_ = session.query(distinct(t.word_desc)).all()

条件
# sql = "SELECT id,ds_desc FROM diais where diaed is NULL GROUP BY id DESC LIMIT 0,1"
rows = session.query(Di.id, Dit.dio).filter(Diaat.diagnosed == None).order_by(desc(Dt.id)).first()

# sql = "SELECT i,c FROM ic ORDER BY LENGTH(wosc) DESC" 可以用char_length来计算字符长度,代替sql 的length长度
standard dict = session.query(I.d, Icc.woc).order_by(
desc(char_length(Ic.wc))).all()

# SELECT * from ic where LIKE %s LIMIT 0,10" like 的用法
rows1 = session.query( d_desc).filter(I.d.like("%" + nrd + "%")).offset(0).limit(12).all()
dict1 = {}
for row in rows1:
row = row._asdict() # tuple 转字典
= row[' ']
old value = dict1.get( )

User.query.filter(User.email.endswith('@example.com')).all()

reverse = session.query(cd_desc).filter(cd_desc. .in_(rlist)).all()

不在列表中(not in), 例如query.filter(~name.in_(['Micheal', 'Bob', 'Jack']))
空值(null), 例如 query.filter(name == None)

与(and), 例如 query.filter(and_(name == 'Andy', fullname == 'Andy Liu' ))

and_可以省略, 例如 query.filter(name=='Andy', fullname==‘Andy Liu')
或(or), 例如 query.filter(or_(name == 'Andy', name == 'Micheal'))

#-------------u
多个更新
session.query(Diat).filter(Diat.id == dsid).update({.mad: reverse s, .dia: 1})
session.rollback()
#-------------d

#------------- sql operation and compex sql

# 聚合查询
print session.query(func.count('*')).select_from(User).scalar()
print session.query(func.count('1')).select_from(User).scalar()
print session.query(func.count(User.id)).scalar()
print session.query(func.count('*')).filter(User.id > 0).scalar() # filter() 中包含 User,因此不需要指定表
print session.query(func.count('*')).filter(User.name == 'a').limit(1).scalar() == 1 # 可以用 limit() 限制 count() 的返回数
print session.query(func.sum(User.id)).scalar()
print session.query(func.now()).scalar() # func 后可以跟任意函数名,只要该数据库支持
print session.query(func.current_timestamp()).scalar()
print session.query(func.md5(User.name)).filter(User.id == 1).scalar()

python sqlalthemy 总结的更多相关文章

  1. Python中的多进程与多线程(一)

    一.背景 最近在Azkaban的测试工作中,需要在测试环境下模拟线上的调度场景进行稳定性测试.故而重操python旧业,通过python编写脚本来构造类似线上的调度场景.在脚本编写过程中,碰到这样一个 ...

  2. Python高手之路【六】python基础之字符串格式化

    Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...

  3. Python 小而美的函数

    python提供了一些有趣且实用的函数,如any all zip,这些函数能够大幅简化我们得代码,可以更优雅的处理可迭代的对象,同时使用的时候也得注意一些情况   any any(iterable) ...

  4. JavaScript之父Brendan Eich,Clojure 创建者Rich Hickey,Python创建者Van Rossum等编程大牛对程序员的职业建议

    软件开发是现时很火的职业.据美国劳动局发布的一项统计数据显示,从2014年至2024年,美国就业市场对开发人员的需求量将增长17%,而这个增长率比起所有职业的平均需求量高出了7%.很多人年轻人会选择编 ...

  5. 可爱的豆子——使用Beans思想让Python代码更易维护

    title: 可爱的豆子--使用Beans思想让Python代码更易维护 toc: false comments: true date: 2016-06-19 21:43:33 tags: [Pyth ...

  6. 使用Python保存屏幕截图(不使用PIL)

    起因 在极客学院讲授<使用Python编写远程控制程序>的课程中,涉及到查看被控制电脑屏幕截图的功能. 如果使用PIL,这个需求只需要三行代码: from PIL import Image ...

  7. Python编码记录

    字节流和字符串 当使用Python定义一个字符串时,实际会存储一个字节串: "abc"--[97][98][99] python2.x默认会把所有的字符串当做ASCII码来对待,但 ...

  8. Apache执行Python脚本

    由于经常需要到服务器上执行些命令,有些命令懒得敲,就准备写点脚本直接浏览器调用就好了,比如这样: 因为线上有现成的Apache,就直接放它里面了,当然访问安全要设置,我似乎别的随笔里写了安全问题,这里 ...

  9. python开发编译器

    引言 最近刚刚用python写完了一个解析protobuf文件的简单编译器,深感ply实现词法分析和语法分析的简洁方便.乘着余热未过,头脑清醒,记下一点总结和心得,方便各位pythoner参考使用. ...

随机推荐

  1. 文件描述符 VS 文件句柄

    文件描述符 VS 文件句柄 文件描述符是标准 C 里用的,是 int 型的,比如调用 open 函数成功后会返回一个与当前文件相关联的 int 型数字. 文件句柄是 Windows 里用的,是 HAN ...

  2. 并行输入\输出控制器之我见(PIO)

    中断信号FIQ及IRQ0到IRQn一般通过PIO控制器复用.但是,由于PIO控制器对于输入无效且中断线(FIQ或IRQ)仅作为输入,因此不必为中断分配I/0线.          电源管理控制器控制P ...

  3. cocoa 运行apple脚本文件的方法

    NSString* path = [[NSBundle mainBundle] pathForResource:@"ScriptName" ofType:@"scpt&q ...

  4. java中静态资源处理方法

    方案一:激活Tomcat的defaultServlet来处理静态文件 在 web.xml 中添加: <servlet-mapping> <servlet-name>defaul ...

  5. Spring MVC-表单(Form)标签-列表框(Listbox)示例(转载实践)

    以下内容翻译自:https://www.tutorialspoint.com/springmvc/springmvc_listbox.htm 说明:示例基于Spring MVC 4.1.6. 以下示例 ...

  6. oracle级联操作

    在加入foreing key约束时,还能够指定级联操作的类型,主要用于确定当删除(on delete) 附表中的一条记录时,怎样处理子表中的外键字段,有例如以下三种引用类型. cascade 此key ...

  7. 被AppStore拒绝理由(一)

    July 8, 2015 at 7:06 AM 发件人 Apple 17.1 - Apps cannot transmit data about a user without obtaining th ...

  8. FZU 1894 志愿者选拔【单调队列】【monotone decreasing queue】

     Problem 1894 志愿者选拔 Accept: 1770    Submit: 5523 Time Limit: 1500 mSec    Memory Limit : 32768 KB  P ...

  9. [POJ 1041] John's Trip

    [题目链接] http://poj.org/problem?id=1041 [算法] 欧拉回路[代码] #include <algorithm> #include <bitset&g ...

  10. EOJ 1501/UVa The Blocks Problem

    Many areas of Computer Science use simple, abstract domains for both analytical and empirical studie ...