【问题标题】:SQLalchemy attribute error when dynamically creating both table and columns names when using string variables使用字符串变量时动态创建表名和列名时的 SQLalchemy 属性错误
【发布时间】:2021-09-18 00:12:47
【问题描述】:

我遇到了需要创建新表和特定列的问题,因为我需要从常规数据表执行 SELECT INTO 到映射表。由于我在数据库中使用的数据的性质,表名和两列名是动态的。

我尝试使用Use variable column headings in SQLAlchemy 中的示例,但仍然出现错误。这是基本代码:

                RecIndex = # some string key value that changes
                tableData = "Data-" + str(i)
                tableName = f'Mapping{idx}'
                colName = f'Voltage{i}-V{idx}'

                col_list = ['Reading', 'Date', colName]
                t_list = {TableData: [RecIndex, colName], tableName: [RecIndex, colName]}
                table_list = []

                for t_name, col_name in t_list.items():
                    t = Table(
                        t_name, metadata,
                        Column('Reading', Integer),
                        Column('Date', Date),
                        *[Column(name, Integer) for name in col_name]
                    )

                    table_list.append(t)

                t1 = table_list[0]      # Mapping table
                t2 = table_list[1]      # Data table

                sel = t1.insert().from_select(col_list, t2.select().where(t2.c.colName > 0))  # FAILS HERE

但是,当我尝试构建 sel 变量时,它会失败并且我收到以下错误消息:

Traceback(最近一次调用最后一次): getattr 中的文件“C:\Python\Python\lib\site-packages\sqlalchemy\sql\base.py”,第 1201 行 返回 self._index[key]

KeyError: 'colName'

sel = t1.insert().from_select(col_list, t2.select().where(t2.c.colName > 0))

getattr 中的文件“C:\Python\Python\lib\site-packages\sqlalchemy\sql\base.py”,第 1203 行 util.raise_(​​AttributeError(key), replace_context=err)

文件“C:\Python\Python\lib\site-packages\sqlalchemy\util\compat.py”,第 207 行,在 raise_ 中 引发异常

属性错误:colName

有人知道为什么它不起作用吗?我会很感激任何帮助

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    在您的示例代码中,您通过变量名称引用列,colName 而不是变量的内容,即。 "Voltage0-V2"。试试这样的:

    sel = t1.insert().from_select(col_list, t2.select().where(getattr(t2.c, colName) > 0))
    

    这只是内置的 getattr: getattr

    我认为dict 样式查找也受支持,即。 t2.c[colName],所以这也可能有效:

    sel = t1.insert().from_select(col_list, t2.select().where(t2.c[colName] > 0))
    

    【讨论】:

    • 两者都成功了。谢谢老兄!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    相关资源
    最近更新 更多