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. Servlet的HttpServletResponse输出

    了解其中的一些字符设置,PrintWriter输出等.. form.html: <!DOCTYPE html> <html> <head> <title> ...

  2. E - Period

    For each prefix of a given string S with N characters (each character has an ASCII code between 97 a ...

  3. Train Problem II HDU 1023 卡特兰数

    Problem Description As we all know the Train Problem I, the boss of the Ignatius Train Station want ...

  4. V - 吉哥系列故事――完美队形I Manacher

    吉哥又想出了一个新的完美队形游戏!  假设有n个人按顺序站在他的面前,他们的身高分别是h[1], h[2] ... h[n],吉哥希望从中挑出一些人,让这些人形成一个新的队形,新的队形若满足以下三点要 ...

  5. firedac的数据序列和还原单元(Data.FireDACJSONReflect.pas)之拷贝FIREDAC数据集

    使用流做中转 procedure CopyDataSet(const ASource, ADest: TFDAdaptedDataSet);var LStream: TStream;begin LSt ...

  6. UVA 12683 Odd and Even Zeroes(数学—找规律)

    Time Limit: 1000 MS In mathematics, the factorial of a positive integer number n is written as n! an ...

  7. UVA 11021 - Tribles(概率递推)

    UVA 11021 - Tribles 题目链接 题意:k个毛球,每一个毛球死后会产生i个毛球的概率为pi.问m天后,全部毛球都死亡的概率 思路:f[i]为一个毛球第i天死亡的概率.那么 f(i)=p ...

  8. 请问在C#的Winform下如何用正则表达式限制用户只能在textBox中输入18位的身份证号码。

    请问在C#的Winform下如何用正则表达式限制用户只能在textBox中输入18位的身份证号码. 2013-06-18 11:07会飞的鱼儿18 | 分类:C#/.NET | 浏览101次 不能有空 ...

  9. spring 监听器 IntrospectorCleanupListener简介

    转自:https://blog.csdn.net/ywb201314/article/details/51144256 其中JavaBeans Introspector是一个类,位置在Java.bea ...

  10. 理解了这些词句涵义用法等,你就熟练ES6了。

    let const 块级作用于 暂时性死区 解构赋值:变量的解构赋值.对象的解构赋值.字符串的解构赋值.数值和布尔值的解构赋值. String的扩展 正则表达式的扩展 Number的扩展 Array的 ...