【问题标题】:SQLALCHEMY can't render element of type <class 'sqlalchemy.dialects.oracle.base.NUMBER'>SQLALCHEMY 无法呈现 <class 'sqlalchemy.dialects.oracle.base.NUMBER'> 类型的元素
【发布时间】:2019-04-29 12:40:21
【问题描述】:

我想使用 sqlalchemy 将一个表从一个 oracle 数据库复制到 postgre 数据库 在 oracle 和 postgre 中设置连接和引擎并将表反映到 sourceMeta 元数据后,我尝试在 destEngine 中创建,但它给了我一个错误,说无法渲染类型的元素...

for t in sourceMeta.sorted_tables:
    newtable = Table(t.name, sourceMeta, autoload=True)
    newtable.metadata.create_all(destEngine)

【问题讨论】:

    标签: python oracle postgresql sqlalchemy


    【解决方案1】:

    看来您正在寻找的是 sqlalchemys @compiles 装饰器。 这是尝试将表从 MS SQL Server 数据库复制到 PostgreSQL 数据库时它如何为我工作的示例。

    from sqlalchemy import create_engine, Table, MetaData
    from sqlalchemy.schema import CreateTable
    from sqlalchemy.ext.compiler import compiles
    from sqlalchemy.dialects.mssql import TINYINT, DATETIME, VARCHAR
    
    @compiles(TINYINT, 'postgresql')
    def compile_TINYINT_mssql_int(element, compiler, **kw):
        """ Handles mssql TINYINT datatype as INT in postgresql """
        return 'INTEGER'
    # add a function for each datatype that causes an error
    
    table_name = '<table_name>'
    
    # create engine, reflect existing columns, and create table object for oldTable
    srcEngine = create_engine('mssql+pymssql://<user>:<password>@<host>/<db>')
    srcEngine._metadata = MetaData(bind=srcEngine)
    srcEngine._metadata.reflect(srcEngine)  # get columns from existing table
    srcTable = Table(table_name, srcEngine._metadata)
    
    # create engine and table object for newTable
    destEngine = create_engine('postgresql+psycopg2://<user>:<password>@<host><db>')
    destEngine._metadata = MetaData(bind=destEngine)
    destTable = Table(table_name.lower(), destEngine._metadata)
    
    # copy schema and create newTable from oldTable
    for column in srcTable.columns:
        dstCol = column.copy()
        destTable.append_column(dstCol)
        # maybe change column name etc.
    print(CreateTable(destTable).compile(destEngine))  # <- check the query that will be used to create the table
    destTable.create()
    

    查看文档: https://docs.sqlalchemy.org/en/13/core/compiler.html 也许还有这个例子: https://gist.github.com/methane/2972461

    【讨论】:

      猜你喜欢
      • 2016-08-16
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 1970-01-01
      相关资源
      最近更新 更多