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()


猜你喜欢

转载自www.cnblogs.com/-aye/p/8984703.html