• python 数据库连接 CRUD


    import sqlalchemy
    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column,String,Integer
    from sqlalchemy.orm.session import sessionmaker
    from sqlalchemy import func
    
    engine = 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
    #  插入数据 , 必须要commit
    Session.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

  • 相关阅读:
    CS academy Binary Flips(dp)
    [POJ 1637] Sightseeing tour(网络流)
    Codeforces 346D Robot Control(01BFS)
    BZOJ 2069: [POI2004]ZAW(Dijkstra + 二进制拆分)
    驱动之SPI,UART,I2C的介绍与应用20170118
    USB驱动之CDC类的介绍与应用20160905
    uCOS-II之移植20160823
    java之面向对象20160818
    Java之基础20160806
    Android之框架20160721
  • 原文地址:https://www.cnblogs.com/412013cl/p/8544137.html
Copyright © 2020-2023  润新知