zoukankan      html  css  js  c++  java
  • SQLAlchemy创建表和删除表

    1、创建引擎

      SQLAlchemy本身无法操作数据库,其必须以来pymsql等第三方插件,Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:

    MySQL-Python
        mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
       
    pymysql
        mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
       
    MySQL-Connector
        mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
       
    cx_Oracle
        oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
       
    更多详见:http://docs.sqlalchemy.org/en/latest/dialects/index.html
    
    以mysql为例:
    engine = create_engine("mysql+pymysql://root:123456@localhost:3306/db4?charset=utf8",
        max_overflow=0,  # 超过连接池大小外最多创建的连接
        pool_size=5,  # 连接池大小
        pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
        pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
        echo = True    # echo参数为True时,会显示每条执行的SQL语句,可以关闭 ",
                                        max_overflow = 5)

    2、创建表

      (1)导入模块,创建Base

    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()

      (2)定义类(一个类为一张表)

    class  User(Base):

    在类中创建列:

      1)表名

    # 这是在数据库中存在的表名
    __tablename__ = 'users'

      2)主键

    id = Column(Integer, primary_key=True,autoincrement=True) #primary_key设置主键,autoincrement=True设置自增

      3)普通字段

    # 32代表最大长度,添加index索引,不可以为null
    name = Column(String(32), index=True, nullable=False)

      4)外键

    #ForeignKeyForeignKey('teacher.tid'),
    teacher_id = Column(Integer,ForeignKey('teacher.tid'))

      5)索引

    # 32代表最大长度,添加index索引,不可以为null
    name = Column(String(32), index=True, nullable=False)

      6)联合唯一索引

       #UniqueConstraint(列明,索引名)
         __table_args__ = (
            UniqueConstraint('tid','tname',name = 'uc_tid'),
        )

      7)联合索引

    __table_args__ = (
            
            # 联合索引
            # Index('ix_id_name', 'name', 'email'),
        )

      8)一对多

    ForeignKey中的参数是表名.要关联的字段,注意这里的表名不是别的类名,而是__tablename__参数值

    默认是同步删除同步更新的,也就是on  delete cascade   on  update  cascade

    hobby_id = Column(Integer, ForeignKey("hobby.id"))

      9)多对多

    要自己创建关系表,分别和其它2张表做forejgnkey

    class Server2Group(Base):
        __tablename__ = 'server2group'
        id = Column(Integer, primary_key=True, autoincrement=True)
        server_id = Column(Integer, ForeignKey('server.id'))
        group_id = Column(Integer, ForeignKey('group.id'))

    3、利用Base的create_all创建表

    Base.metadata.create_all(engine)

      删除表:

    注意注意删除一定要慎重,利用Base的drop_all删除表

    Base.metadata.drop_all(engine)

    例:

    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
    engine = create_engine("mysql+pymysql://root:123456@localhost:3306/db4",
                                        max_overflow = 5) #创建引擎
    Base = declarative_base()                   #创建Base
    
    class Teacher(Base):            #创建表
        __tablename__ = 'teacher'   #表名
        tid = Column(Integer,nullable= False,primary_key = True,autoincrement= True) #整型,不为空,主键,自增
        sname = Column(String(32),index=True)   #字符串(32),普通索引
        gender = Column(String(2))              
    
        __table_args__ = (
            UniqueConstraint('tid',name = 'uc_tid'),    #唯一索引
        )
    
    class Student(Base):
        __tablename__ = 'student'
        sid = Column(Integer,primary_key = True,autoincrement= True)
        sname = Column(String(32),index=True)
        gender = Column(String(2))
        teacher_id = Column(Integer,ForeignKey('teacher.tid'))      #外键
    
    
    def init_db(): #初始化表
        Base.metadata.create_all(engine)
    
    def drop_db():  #删除表
        Base.metadata.drop_all(engine)
    
    
    init_db() #创建表
    # drop_db() #删除表
  • 相关阅读:
    教师资格证考试全部重点名词解释
    计算机软考中高级职称评定条件
    如何计算教师工龄?工龄和教龄的区别
    vue.js中 this.$nextTick()的使用
    数组的合并 总结的几种方法
    CSS3实现了左右固定中间自适应的几种方法
    文本溢出省略号
    MVC/MVP/MVVM
    vue中父组件给子组件传值的方法
    vue实例的生命周期
  • 原文地址:https://www.cnblogs.com/aizhinong/p/11745209.html
Copyright © 2011-2022 走看看