【问题标题】:SQLAlchemy python copying table identically and pasting it elsewhereSQLAlchemy python相同地复制表并将其粘贴到其他地方
【发布时间】:2020-05-22 02:43:33
【问题描述】:

我有一个 MySQL 数据库,它有一个主键为 VARCHAR(4) 的表,并且包含 10 个包含 FLOAT 的列。 我试图复制表格并将其粘贴到其他地方,但是当 read_sql() 时,它会改变表格的格式,例如将 VARCHAR(4) 和 FLOAT 更改为 TEXT 并将过去的主键更改为常规列。最后它添加了一个索引。 我的问题是,我怎样才能以相同的方式复制表,对数据进行更改,并将其写入另一个具有相似格式的数据库。

【问题讨论】:

    标签: python mysql sqlalchemy read-sql


    【解决方案1】:

    您的问题暗示您正在寻找基于 SQLAlchemy 的表迁移。通常,我会改用mysqldump 之类的实用程序。我做了一些搜索并成功测试了一个基于 SQLAlchemy 的解决方案。使用来自https://www.paulsprogrammingnotes.com/2014/01/clonecopy-table-schema-from-one.html的这个配方

    from sqlalchemy import create_engine, Table, Column, Integer, Unicode, MetaData, String, Text, update, and_, select, func, types
    
    # create engine, reflect existing columns, and create table object for oldTable
    srcEngine = create_engine('mysql+mysqldb://username:password@111.111.111.111/database') # change this for your source database
    srcEngine._metadata = MetaData(bind=srcEngine)
    srcEngine._metadata.reflect(srcEngine) # get columns from existing table
    srcTable = Table('oldTable', srcEngine._metadata)
    
    # create engine and table object for newTable
    destEngine = create_engine('mysql+mysqldb://username:password@localhost/database') # change this for your destination database
    destEngine._metadata = MetaData(bind=destEngine)
    destTable = Table('newTable', destEngine._metadata)
    
    # copy schema and create newTable from oldTable
    for column in srcTable.columns:
        destTable.append_column(column.copy())
    destTable.create()
    

    您需要将连接字符串替换为您自己的,并将表名更改为您自己的。

    【讨论】:

      猜你喜欢
      • 2020-08-18
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      相关资源
      最近更新 更多