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() #刪除表

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM