python-3.x 如何用SQL炼金术克隆表

2ul0zpep  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(137)

我有一个在SQLAlchemy中没有模型的表,例如,我的数据库中的names,我想用新名称names_clone克隆它。如何在SQLAlchemy中实现这一点而不使用SQLAlchemy模型?

db_url = "some DB URL engine"
engine = create_engine(db_url)
meta = MetaData(bind=engine)
inspector = inspect(engine)
table = Table("names", meta, autoload=True)
# I want do some thing like blow
new_table = table.copy

字符串

mum43rcc

mum43rcc1#

我这样写代码,

columns = []
for column in table.columns:
    columns.append(Column(column.name, column.type, primary_key=column.primary_key,
                              autoincrement=column.autoincrement))
new_table = Table(
    new_name, meta
    , *columns
)
result = meta.create_all(engine, tables=[new_table])

query = new_table \
    .insert() \
    .from_select(names=[column.name for column in new_table.columns],
                 # array of column names that your query returns
                 select=select([table]))

result = connection.execute(query)

字符串

相关问题