zoukankan      html  css  js  c++  java
  • Python9-MySQL-MySQL-ORM框架-day48

    ORM框架:AQLAlchemy
    -作用:
    1、提供简单的规则
    2、自动转换成SQL语句

    -DB first: 手动创建数据库以及表 -> ORM框架 -> 自动生成类
    code first:手动创建类 ->ORM框架 -> 以及表
    功能:
    -创建数据库表
    连接数据库(非SQLAlchemy,是pymsql)
    类转换SQL语句
    -操作数据行



    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
    from sqlalchemy.orm import sessionmaker, relationship
    from sqlalchemy import create_engine
    
    Base = declarative_base()
    # 创建单表
    class UserType(Base):
        __tablename__ = 'usertype'
        id = Column(Integer, primary_key=True,autoincrement=True)
        name = Column(String(32),nullable=True,default='sf',index=True)
    
    class Users(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True,autoincrement=True)
        name = Column(String(32),nullable=True,default='sf',index=True)
        extra = Column(String(16),unique=True)
        user_type_id = Column(Integer,ForeignKey('usertype.id'))
    def create_db():
        engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
        Base.metadata.create_all(engine)
    def delete_db():
        engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
        Base.metadata.drop_all(engine)
    #增加
    obj1 = UserType(name='普通用户')
    session.add(obj1)
    session.commit()
    # obj1 = UserType(name='普通用户')
    objs=[
         UserType(name='超级用户'),
         UserType(name='白金用户'),
         UserType(name='黑金用户')
    ]
    # session.add(obj1)
    session.add_all(objs)
    session.commit()
    session.close()
    #修改
    # session.query(UserType.id,UserType.name).filter(UserType.id>0).update({'name':'黑金'})
    session.query(UserType.id,UserType.name).filter(UserType.id>2).update({UserType.name: UserType.name + "xxx"}, synchronize_session=False)
    session.commit()
    session.close()
    

      

    #
    # session.query(UserType.id,UserType.name).filter(UserType.id>3).delete()
    #
    # user_type_list = session.query(UserType).all()
    # for row in user_type_list:
    #     print(row.id,row.name)
    # user_type_list = session.query(UserType.id,UserType.name).filter(UserType.id>2)
    # for row in user_type_list:
    #     print(row.id,row.name)
  • 相关阅读:
    There is an overlap in the region chain修复
    There is an overlap in the region chain
    region xx not deployed on any region server
    python 中的re模块,正则表达式
    TCP粘包问题解析与解决
    yield from
    Git push提交时报错Permission denied(publickey)...Please make sure you have the correct access rights and the repository exists.
    mysql 中Varchar 与char的区别
    Mysql 字符集及排序规则
    请实现一个装饰器,限制该函数被调用的频率,如10秒一次
  • 原文地址:https://www.cnblogs.com/zhangtengccie/p/10490569.html
Copyright © 2011-2022 走看看