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::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::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() #删除表
相关推荐
liuweiq 2020-06-14
emmm00 2020-06-14
lt云飞扬gt 2020-05-29
朱建伟 2020-05-14
猛禽的编程艺术 2020-05-06
苦咖啡flask 2020-05-04
dreamhua 2020-04-30
dreamhua 2020-04-30
tanrong 2020-04-30
xuanlvhaoshao 2020-04-26
tanrong 2020-04-18
Danialzhou 2020-04-11
happinessaflower 2020-03-01
xiaoxiangyu 2020-02-23
喝绿茶的猫 2020-01-18
疯狂老司机 2020-01-10
liuyang000 2020-01-08
Lingforme 2020-01-08