使用字符串变量时动态创建 table 和列名时出现 SQLalchemy 属性错误

SQLalchemy attribute error when dynamically creating both table and columns names when using string variables

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

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

                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 (most recent call last): File "C:\Python\Python\lib\site-packages\sqlalchemy\sql\base.py", line 1201, in getattr return self._index[key]

KeyError: 'colName'

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

File "C:\Python\Python\lib\site-packages\sqlalchemy\sql\base.py", line 1203, in getattr util.raise_(AttributeError(key), replace_context=err)

File "C:\Python\Python\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_ raise exception

AttributeError: colName

有人知道为什么它不起作用吗?我将不胜感激

在您的示例代码中,您通过变量名称 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))