使用sqlalchemy创建表及删除表

一、创建表

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,String,Integer

dbUrls=basics.dbUrls()

engine = create_engine(dbUrls,echo=True,max_overflow=5)
#连接mysql数据库,echo为是否打印结果

Base = declarative_base() #生成orm基类
 
class Position(Base): #继承生成的orm基类
    __tablename__ = "position" #表名
    id = Column(Integer,primary_key=True) #设置主键
    symbol = Column(String(20))  # 交易对
    side = Column(String(20))  # 方向
    size = Column(String(20))  # 仓位数量
    position_value = Column(String(20))  # 仓位价值
    entry_price = Column(String(20))  # 平均入场价
    liq_price = Column(String(20))  # 强平价格
 
class CutLoss(Base):
    __tablename__ = "cut_loss"
    id = Column(Integer, primary_key=True)
    symbol = Column(String(20))  # 交易对
    intervention_rate = Column(String(20))  # 介入风险率
    profit_margin = Column(String(20))  # 对冲利润率
 
Base.metadata.create_all(engine) #创建表结构

二、删除表

drop_all(),删除了所有结构(),而不仅仅是一个特定的表:

Base.metadata.drop_all(engine)   # all tables are deleted

使用SQLAlchemy通过engine.execute()方法执行原始SQL :

sql = text('DROP TABLE IF EXISTS my_users;')
result = engine.execute(sql)

调用drop()表对象,使用给定的Connectable进行连接,为此Table发出DROP语句。

User.__table__.drop()

如果得到一个例外:

sqlalchemy.exc.UnboundExecutionError: Table object 'my_users' is not bound to an Engine or Connection. Execution can not proceed without a database to execute against

则需要通过引擎:

User.__table__.drop(engine)

版权声明:本文为xkyykx原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。