通过 Set Comprehension 使用 pyodbc 从 SQL 检索数据给出不可散列的类型:'pyodbc.Row'

Retrieving Data from SQL Using pyodbc through Set Comprehension gives unhashable type: 'pyodbc.Row'

我需要 运行 SELECT 声明一组文件列表。我正在使用以下代码片段:

def flist_in_psumsdb(config, fnames_set_in_psumsdictlist):
    constring = config['db_string## Heading ##']['db_string']
    cnxn = pyodbc.connect(constring)
    cnxnset = {  row for row in  {(cnxn.execute(f"""SELECT LOG FROM {config['db_string']['bd_psums_meta_table_str']} where LOG = '{log}'  """)).fetchone() for log in fnames_set_in_psumsdictlist} }
    cnxn.close()

然而,当我 运行 出现此错误时:

  File "c:\Users\sys_nsgprobeingestio\Documents\dozie\odfs\etesthad4.py", line 458, in <setcomp>
    cnxnset = {  row for row in       {(cnxn.execute(f"""SELECT LOG FROM {config['db_string']['bd_psums_meta_table_str']} where LOG = '{log}'  """)).fetchone() for log in fnames_set_in_psumsdictlist} }
TypeError: unhashable type: 'pyodbc.Row'

想法是循环访问 cnxset 和 return 来自 pyodbc 行的日志文件列表,如下所示:

filelist = {row.LOG for row in cnxnset}

其中 LOG 当然是来自 sql select 语句

的列

给定一个可迭代的日志名称,可以使用 IN 查询检索它们。

首先,我们需要构建值替换子句:

names = fnames_set_in_psumsdictlist

subs = ', '.join(['?' for name in names])

现在我们可以构建完整的查询并执行它。

q = f"""SELECT LOG 
FROM {config['db_string']['bd_psums_meta_table_str']} 
WHERE LOG IN ({subs}); """

cursor.execute(q, names)
rows = cursor.fetchall()

请注意,不同的数据库驱动程序具有不同的替换参数 - pyodbc 使用 '?',其他一些使用 '%s'。使用替换参数而不是字符串插值可确保在查询中正确引用值。