sqlalchmy动态创建表和动态反向映射获取model

根据表名动态创建表

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker


engine = create_engine('sqlite:///' + db_path, echo=False)
Base = declarative_base()
Session = sessionmaker(bind=engine)
dbSession = Session()
def create_table(tb_name, item):
    """表名,创建新表"""
    tb_str = "CREATE TABLE if not exists " + tb_name + """(
    id INTEGER NOT NULL,
    """
    for key, value in parameters.items():
        tb_str += key + ' ' + value + """,
    """
    tb_str += '''robot_id INTEGER,
    PRIMARY KEY (id),
    FOREIGN KEY(robot_id) REFERENCES user_robot (robot_id) ON DELETE CASCADE)'''
    dbSession.execute(tb_str)  # 执行sql语句
    return True

动态获取模型

def getModel(name):
    """根据表名name动态创建并return一个新的model类
    name:数据库表名
    engine:create_engine返回的对象,指定要操作的数据库连接,from sqlalchemy import create_engine
    """
    Base.metadata.reflect(engine)
    table = Base.metadata.tables[name]
    t = type(name, (object,), dict())
    mapper(t, table)
    Base.metadata.clear()
    return t

你可能感兴趣的:(sqlalchmy动态创建表和动态反向映射获取model)