python---ORM之SQLAlchemy(1)

定义一个类,ORM(对象关系映射)将这个类转换为sql语句,使用pymysql进行执行

一,底层处理

使用engine/connectionpooling/dialect进行数据库操作,engine使用connectionpooling连接数据库,然后在通过dialect执行sql语句(SQLAlchemy本身无法操作数据库,其必须以来pymsql等第三方插件,Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API)

pymysql
    mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://root:root@127.0.0.1:3306/t1",max_overflow=5)

二,创建一个单表

import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Column,Integer,String
from sqlalchemy import and_,or_
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine("mysql+pymysql://root:root@127.0.0.1:3306/t1")

Base = declarative_base()#生成一个SQLORM基类

class User(Base):
    __tablename__ = "users"

    id = Column(Integer,primary_key=True,autoincrement=True)
    name = Column(String(40))
    fullname = Column(String(40))
    password = Column(String(40))

    def __repr__(self):
        return "<User(name='%s', fullname='%s',password='%s')>"%(self.name,self.fullname,self.password)

Base.metadata.create_all(engine)#创建所有表结构
#Base.metadata.drop_all(engine)#删除所有的表

ed_user = User(name='xiaoyu',fullname='xiaoudaf',password='123')

MySession = sessionmaker(bind=engine)
session=MySession()

#一次加入一条
# session.add(ed_user)

#一次加入多条
# session.add_all([
#     User(name='daf',fullname='fafwaf',password='fwa'),
#     User(name='daf', fullname='fafwaf', password='fwa'),
#     User(name='daf', fullname='fafwaf', password='fwa'),
# ])
#
# session.commit()

#查询所有
print(session.query(User).all())
#按顺序查询
for row in session.query(User).order_by(User.id):
    print(row)

#进行过滤
for row in session.query(User).filter(User.name.in_(['xiaoyu',])):
    print(row)

for row in session.query(User).filter(~User.name.in_(['xiaoyu', ])):
    print(row)

for row in session.query(User).filter(User.name=='xiaoyu'):
    print(row)

print(session.query(User).filter(User.name=='xiaoyu').count())


for row in session.query(User).filter(and_(User.name=='daf',User.fullname=='fafwafs')):
    print(row)

for row in session.query(User).filter(or_(User.name=='daf',User.fullname=='xiaoudafc')):
    print(row)

 

posted @ 2018-03-13 19:28  山上有风景  阅读(372)  评论(0编辑  收藏  举报