sqlalchemy根据表名动态创建model类作⽤如题,直接上代码吧,另外还⽀持 copy⼀张表的表结构,新建表并获得model对象
# coding: utf-8
import traceback
from sqlalchemy import (BigInteger, Column, DateTime, Integer, MetaData,
String, Table, create_engine, text)
declarative import declarative_base
import mapper
from sqlalchemy.schema import CreateTable
# 本地数据库
engineLocal = create_engine('mysql+pymysql://root:root@127.0.0.1:3306/lingyun?charset=utf8')
Base = declarative_base()
metadata = MetaData()
def dictToObj(results, to_class):
"""将字典list或者字典转化为指定类的对象list或指定类的对象
python ⽀持动态给对象添加属性,所以字典中存在⽽该类不存在的会直接添加到对应对象
"""
if isinstance(results, list):
objL = []
for result in results:
obj = to_class()
for r in result.keys():
obj.__setattr__(r, result[r])
objL.append(obj)
return objL
else:
try:
obj = to_class()
for r in results.keys():
obj.__setattr__(r, results[r])
return obj
except Exception as e:
print(e)
traceback.print_exc()
return None
# else:
# print("传⼊对象⾮字典或者list")
# return None
def getModel(name, engine):
"""根据name创建并return⼀个新的model类
name:数据库表名sql语句替换表中内容
engine:create_engine返回的对象,指定要操作的数据库连接,from sqlalchemy import create_engine
"""
table = adata.tables[name]
t = type(name,(object,),dict())
mapper(t, table)
return t
def createTableFromTable(name, tableNam, engine):
"""copy⼀个已有表的结构,并创建新的表
"""
metadata = MetaData(engine)
# 获取原表对象
table = adata.tables[tableNam]
# 获取原表建表语句
c = str(CreateTable(table))
# 替换表名
c = c.replace("CREATE TABLE " + tableNam, "CREATE TABLE if not exists " + name)
db_conn = t()
ute(c)
db_conn.close()
def getNewModel(name, tableNam, engine):
"""copy⼀个表的表结构并创建新的名为name的表并返回model类
name:数据库表名
tableNam:copy的表表名
engine:create_engine返回的对象,指定要操作的数据库连接,from sqlalchemy import create_engine """
createTableFromTable(name, tableNam, engine)
return getModel(name, engine)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论