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:[email protected]: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:[email protected]: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() #删除表

原文地址:https://www.cnblogs.com/aizhinong/p/11745209.html

时间: 2024-08-01 06:47:44

SQLAlchemy创建表和删除表的相关文章

创建表,创建数据库, 删除表 ,删除数据库

创建表,创建数据库, 删除表 ,删除数据库 创建数据库 Create  database  text2  创建数据库text2 2. 删除数据库 Drop  database   text2  删除数据库text2 创建表 Create  table class   创建一个表叫class                  这是个主表 ( Code  varchar(20)  primary key,                                     创建序号 Name  

sql 创建表、删除表 增加字段 删除字段操作

[转]sql 创建表.删除表 增加字段 删除字段操作 下面是Sql Server 和 Access 操作数据库结构的常用Sql,希望对你有所帮助. 新建表:create table [表名]([自动编号字段] int IDENTITY (1,1) PRIMARY KEY ,[字段1] nVarChar(50) default \'默认值\' null ,[字段2] ntext null ,[字段3] datetime,[字段4] money null ,[字段5] int default 0,[

python pynssql创建表,删除表,插入数据,查询

import pymssql server='10.194.**.***:*****' user='sa' password='******' database='******' #连接 conn=pymssql.connect(server,user,password,database) print(server) cursor=conn.cursor() #get cursor print('connect to db success') #创建表,删除表 cursor.execute("&

删除表及删除表中数据的方法

本文介绍SQL Server中如何删除表,如何删除表中的数据.在删除表数据时有delete和truncate两种方法,delete和truncate有什么区别呢? SQL Server,我们现在基本上使用的最古老的版本应该是SQL Server 2000吧,应该没有更早的版本了吧?!从SQL Server 2000开始,到SQL Server 2005,2008,2012等,T-SQL的处理能力越来越强.今天我们就来说说如何使用T-SQL脚本来删除表,以及删除表中的数据. 删除表和删除表数据这是

MySQL删除表及删除表数据操作

MySQL删除表和删除表的数据是常见的操作,使用关键词 DELETE FROM 表名的结构模式,下面详细讲述删除表和删除表数据. 1,删除数据库里面的表 DELETE FROM employees; 2,删除数据库里面的表数据 DELETE FROM huthon WHERE id = 4; 注意删除多个id 应该用 id in (4,5,6) 模式 文章来自:http://www.huthon.cn/ 原文地址:http://blog.51cto.com/13959155/2176543

python 之 数据库(修改表、复制表、删除表、单表查询)

10.8 修改表.复制表.删除表 10.81 修改表 alter table 1. 修改表名 alter table 表名 rename 新表名; 2. 增加字段 alter table 表名 add 字段名 数据类型 [完整性约束条件…]; alter table t1 add stu char(10) not null after name; #添加到name字段之后 alter table t1 add sex enum('male','female') default 'male' fi

SQLALchemy之创建表,删除表

1.创建引擎 "数据库+第三方模块://用户名:密码@数据库服务端IP:端口号/数据库名?编码" engine = create_engine( "mysql+pymysql://root:[email protected]:3306/t1?charset=utf8", max_overflow=0, # 超过连接池大小外最多创建的连接 pool_size=5, # 连接池大小 pool_timeout=30, # 池中没有线程最多等待的时间,否则报错 pool_r

MySQL创建表和删除表

创建表 简单的方式 CREATE TABLE person ( number INT(11), name VARCHAR(255), birthday DATE ); 或者是 CREATE TABLE IF NOT EXISTS person ( number INT(11), name VARCHAR(255), birthday DATE ); 查看mysql创建表: SHOW CREATE table person; CREATE TABLE `person` ( `number` int

MySQL学习笔记-查看表,修改表,删除表

/*看表*/ describe test --查看表的结构 show create table test --查看表的创建语句 show create table test  \G --将创建的语句查询出来,并规范化显示(只在console下支持此命令,因为只有console下会错乱显示...) /*改表*/ alter table test rename to testo; --将test改名为testo alter table example0 rename to user; select