通过集合理解使用 pyodbc 从 SQL 检索数据给出了不可哈希的类型:'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:Userssys_nsgprobeingestioDocumentsdozieodfsetesthad4.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,并从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'。使用替换参数而不是字符串插值可以确保在查询中正确引用值。

最新更新