import sqlalchemyfrom sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column,String,Integerfrom sqlalchemy.orm.session import sessionmakerfrom sqlalchemy import funcengine = create_engine('mysql+pymysql://root:412013@localhost/testdb?charset=utf8',echo=False)Base = declarative_base() # 生产orm基类class User(Base): __tablename__ = 'user' # 表名 id = Column(Integer, primary_key=True) name = Column(String(32)) # varchar(32) password = Column(String(64)) # varchar(64) def __init__(self,name,password): self.name = name self.password = password def __repr__(self): return '<@user:[name=%s,password=%s]> ' %(self.name,self.password)Base.metadata.create_all(engine) # 不存在创建数据表Session_class = sessionmaker(bind=engine) # 创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例Session = Session_class() # 生产session实例user_obj = User(name='kaige',password='123456') # 生成你要创建的数据对象print(user_obj.name, user_obj.id) # 此时还没创建对象呢,打印一下id发现还是None# 插入数据 , 必须要commitSession.add(user_obj) # 把要创建的数据对象添加到这个session里, 一会统一创建print(user_obj.name, user_obj.id) # 此时也依然还没创建# 提交数据Session.commit()# Session.rollback() 回滚# 查询 一条# my_user = Session.query(User).filter_by(name='kaige').first()# 查询所有# my_user = Session.query(User).filter(User.name=='kaige').all()# 修改# my_user = Session.query(User).filter_by(name='kaige').first()# my_user.name = 'I love you22222222'# Session.commit() # 修改插入需要commit# 包含多个条件# my_user = Session.query(User).filter(User.name.in_(['kaige', 'I love you'])).all()# 模糊查询# my_user = Session.query(User).filter(User.name.like("I%")).all()# 统计# my_user = Session.query(User).filter(User.name == 'kaige').count()# 分组''' SELECT count(user.name) AS count_1, user.name AS user_name FROM user GROUP BY user.name'''# print(Session.query(func.count(User.name),User.name).group_by(User.name).all() )# 输入结果 : [(1, 'I love you'), (2, 'I love you22222222'), (19, 'kaige')]# Session.query(User).filter(User.name.in_(['Jack','rain'])).all()print(my_user)
http://www.cnblogs.com/alex3714/articles/5978329.html