首页 > 解决方案 > sqlalchemy.exc.ArgumentError:select() 的列参数必须是 Python 列表或其他可迭代对象

问题描述

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

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 文件是否在表中,并且只返回一个真值或假值供我用作重复检查?

标签: pythonsql-serverpython-3.xsqlalchemy

解决方案


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

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'])

推荐阅读