• SQLAlchemy MySQL 增删改查


    from sqlalchemy import Column, Integer, VARCHAR, create_engine
    from sqlalchemy.orm import declarative_base, sessionmaker
    
    Base = declarative_base()
    
    
    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        name = Column(VARCHAR(256), nullable=False)
        age = Column(Integer)
        place = Column(VARCHAR(256), nullable=False)
    
        def __init__(self, id, name, age, place):
            self.id = id
            self.name = name
            self.age = age
            self.place = place
    
    
    def get_engine():
        return create_engine(
            "mysql+pymysql://root:luckygxf@localhost:3306/test",
            encoding="utf-8",
            echo=True
        )
    
    
    def init_db():
        engine = get_engine()
        Base.metadata.create_all(engine)
        print('Create table successfully!')
    
    
    def get_session():
        engine = get_engine()
        db_session = sessionmaker(bind=engine)
        return db_session()
    
    
    def add_user(user):
        session = get_session()
        session.add(user)
        session.commit()
        session.close()
    
    
    def query_user():
        session = get_session()
        users = session.query(User).all()
        session.close()
        return users
    
    
    def print_all(users):
        names = [user.name for user in users]
        print(names)
    
    
    def update_user():
        session = get_session()
        session.query(User).filter(User.name == 'zhangsan').update({"place": "Shanghai"})
        session.commit()
        session.close()
    
    
    def delete_user(user_id):
        session = get_session()
        session.query(User).filter(User.id == user_id).delete()
        session.commit()
        session.close()
    
    
    if __name__ == '__main__':
        # init_db()
        # zhangsan = User(1, 'zhangsan', 18, 'Chengdu')
        # lisi = User(2, 'lisi', 19, 'Beijing')
        # add_user(lisi)
        # users = query_user()
        # print_all(users)
        # update_user()
        delete_user(1)
    Please call me JiangYouDang!
  • 相关阅读:
    在C#程序中模拟发送键盘按键消息
    C# UDPCLIENT多线程实例
    【转】WINFORM下FTP客户端的实现
    抓取屏幕或窗体并保存成图片
    c# 判断窗体已打开则显示为焦点
    【转】C#中dataGridView用法实例分析
    【转】VC6控件小记
    .Net部署二三事之一——如何为VS安装文件MSI制作更新补丁MSP
    [转]C#串口serialPort操作
    VS向IIS发布C#或VB应用程序
  • 原文地址:https://www.cnblogs.com/luckygxf/p/15058907.html
Copyright © 2020-2023  润新知