【问题标题】:sqlalchemy.exc.ArgumentError: columns argument to select() must be a Python list or other iterablesqlalchemy.exc.ArgumentError:select() 的列参数必须是 Python 列表或其他可迭代对象
【发布时间】:2020-10-15 08:36:12
【问题描述】:

Python 和 SQLquery 的新手。我正在尝试查询 mssql 中的现有表。第一个任务是显示表中的内容,我还想做的另一个任务是执行 exists() 语句来检查表中的数据是否确实存在。到目前为止,这些是我的代码 sn-ps:

def dbhandler():
    params = urllib.parse.quote_plus(db_string)
    engine = db.create_engine("mssql+pyodbc:///?odbc_connect={}".format(params))

    connection = engine.connect()
    metadata = db.MetaData()
    odfs_tester_history_files = db.Table('odfs_tester_history_files', metadata, autoload=True, autoload_with=engine)
    odfs_tester_history = db.Table('odfs_tester_history', metadata, autoload=True, autoload_with=engine)
    tables_dict = {'odfs_tester_history_files': {'engine': engine, 'connection': connection, 'table': odfs_tester_history_files}, 'odfs_tester_history': {'engine': engine, 'connection': connection, 'table': odfs_tester_history}}
    #return {'engine': engine, 'connection': connection, 'table': odfs_tester_history_files}
    return tables_dict

db_instance = dbhandler()
odfs_tabletest_dict = db_instance['odfs_tester_history']
foo_col = db.sql.column('CSV_FILENAME')
sql = db.select(odfs_tabletest_dict['table']).where(odfs_tabletest_dict['odfs_tester_history'].c.foo_col == '06_16_2020_FMGN519.csv')
df = pd.read_sql(sql, odfs_tabletest_dict['connection'])
print(df)

但是,当我运行代码时,出现以下错误:sqlalchemy.exc.ArgumentError:select() 的列参数必须是 Python 列表或其他可迭代对象。我怎样才能解决这个问题?另外我如何使用存在语句来检查有问题的数据,.csv 文件是否在表中,并且只返回一个真值或假值供我用作重复检查?

【问题讨论】:

  • 哇,没人知道吗?
  • 就我而言,我通过将 sqlalchemy 包升级到最新版本解决了这个问题。

标签: python sql-server python-3.x sqlalchemy


【解决方案1】:

万一有人遇到这个问题,我通过在我的表格对象周围放置方括号来修复它。我不知道为什么会这样,我的导师也不知道。他有类似的代码,并且不需要 [ ] 就可以为他工作。

sql = db.select([odfs_tabletest_dict['table']]).where(odfs_tabletest_dict['table'].c.CSV_FILENAME == '06_16_2020_FMGN519.csv')
df = pd.read_sql(sql, odfs_tabletest_dict['connection'])

【讨论】:

  • 请注意正在使用的 SQLAlchemy 版本。 select 方法正在更改中,因此如果您使用的是 1.3.x,而您的导师使用的是最新的 master 分支(最终将变为 1.4,之后将变为 2.0),那么您可能会遇到不同的行为。
  • 原因是因为版本1.3.x将此文档与[]docs.sqlalchemy.org/en/13/core/tutorial.html一起使用
【解决方案2】:

Gord Thompson 对 this 的评论帮助我解决了这个问题。我升级到 SQLAlchemy 1.4.11 并摆脱了这个问题。

【讨论】:

    【解决方案3】:

    如果有人仍然面临这个问题,正如前面提到的那样,请注意版本,

    我使用的是 '1.3.10' 版本,您需要将 model.columns 传递给 select()

    model = db.Table('my_table_name', metadata, autoload=True, autoload_with=engine)
    query = db.select(model.columns)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-06
      • 2014-04-26
      • 1970-01-01
      • 2017-05-17
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      相关资源
      最近更新 更多