python sqlalthemy 总结
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 总结的更多相关文章
- Python中的多进程与多线程(一)
一.背景 最近在Azkaban的测试工作中,需要在测试环境下模拟线上的调度场景进行稳定性测试.故而重操python旧业,通过python编写脚本来构造类似线上的调度场景.在脚本编写过程中,碰到这样一个 ...
- Python高手之路【六】python基础之字符串格式化
Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...
- Python 小而美的函数
python提供了一些有趣且实用的函数,如any all zip,这些函数能够大幅简化我们得代码,可以更优雅的处理可迭代的对象,同时使用的时候也得注意一些情况 any any(iterable) ...
- JavaScript之父Brendan Eich,Clojure 创建者Rich Hickey,Python创建者Van Rossum等编程大牛对程序员的职业建议
软件开发是现时很火的职业.据美国劳动局发布的一项统计数据显示,从2014年至2024年,美国就业市场对开发人员的需求量将增长17%,而这个增长率比起所有职业的平均需求量高出了7%.很多人年轻人会选择编 ...
- 可爱的豆子——使用Beans思想让Python代码更易维护
title: 可爱的豆子--使用Beans思想让Python代码更易维护 toc: false comments: true date: 2016-06-19 21:43:33 tags: [Pyth ...
- 使用Python保存屏幕截图(不使用PIL)
起因 在极客学院讲授<使用Python编写远程控制程序>的课程中,涉及到查看被控制电脑屏幕截图的功能. 如果使用PIL,这个需求只需要三行代码: from PIL import Image ...
- Python编码记录
字节流和字符串 当使用Python定义一个字符串时,实际会存储一个字节串: "abc"--[97][98][99] python2.x默认会把所有的字符串当做ASCII码来对待,但 ...
- Apache执行Python脚本
由于经常需要到服务器上执行些命令,有些命令懒得敲,就准备写点脚本直接浏览器调用就好了,比如这样: 因为线上有现成的Apache,就直接放它里面了,当然访问安全要设置,我似乎别的随笔里写了安全问题,这里 ...
- python开发编译器
引言 最近刚刚用python写完了一个解析protobuf文件的简单编译器,深感ply实现词法分析和语法分析的简洁方便.乘着余热未过,头脑清醒,记下一点总结和心得,方便各位pythoner参考使用. ...
随机推荐
- Jquery书写ajax
根据API学习本章 Jquery书写ajax 使用ajax发送表单到servlet,发送时显示等待图片,servlet处理完返回信息,在页面显示返回信息,并且隐藏等待图片 <%@ page la ...
- P - How many
Give you n ( n < 10000) necklaces ,the length of necklace will not large than 100,tell me How man ...
- SSM(spring mvc+spring+mybatis)学习路径——2-2、spring MVC拦截器
目录 2-2 Spring MVC拦截器 第一章 概述 第二章 Spring mvc拦截器的实现 2-1 拦截器的工作原理 2-2 拦截器的实现 2-3 拦截器的方法介绍 2-4 多个拦截器应用 2- ...
- 搭建LVS+Keepalived负载均衡集群
这两天学习了LVS+Keepalived负载均衡的搭建.网上的教程非常多,可是动起手来遇到不少问题. 如今把自己的搭建过程以及遇到的一些问题给分享下. 硬件环境: Macbook 8G内存.250G ...
- java读取中文分词工具(一)
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.I ...
- Unique Paths I,II
题目来自于:https://leetcode.com/problems/unique-paths/ :https://leetcode.com/problems/unique-paths-ii/ A ...
- requireJS使用shim注入非标准模块详解
在javascript中定义全局变量有2种方式,本质上是等价的,都是向window对象注入属性或者方法. // global.js var g_name = "aty"; wind ...
- 怎样使用ListView实现一个带有网络请求,解析,分页,缓存的公共的List页面来大大的提高工作效率
在寻常的开发中常常会有非常多列表页面.每做一个列表页就须要创建这个布局文件那个Adapter适配器文件等等一大堆与之相关的附属的不必要的冗余文件. 假设版本号更新迭代比較频繁,如此以往,就会使项目pr ...
- linux下查看监听port相应的进程
使用netstat查看进程PID [root@test ~]# netstat -anp|grep 5001 tcp 0 0 :::5001 :::* LISTEN 12886/java 之后各位看官 ...
- DBI(i80)/DPI(RGB)/DSI【转】
本文转载自:http://blog.csdn.net/liuxd3000/article/details/17437317 (1)DBI接口 A,也就是通常所讲的MCU借口,俗称80 system接口 ...