我正试图传递一个要在WHERE-in语句中使用的值元组,这就是cursor.mogrify()返回给我的:

b'SELECT site_id,site_name,date,time,* FROM "SiteInfoSchema"."Compressor"
WHERE site_id in (\'TSE-000027, TSE-000032, TSE-000030, TSE-000031, TSE-
000034, TSE-000033, TSE-000019, TSE-000020, TSE-000055, TSE-000021, TSE-
000036, TSE-000035, TSE-000070, TSE-000003, TSE-000047, TSE-000029, TSE-
000023, TSE-000038, TSE-000045, TSE-000046, TSE-000024, TSE-000022, TSE-
000025, TSE-000028, TSE-000026, TSE-000017, TSE-000069, TSE-000054, TSE-
000037, TSE-000018\') AND device_id = \'1\' AND date >= \'2018-05-02\' and
date <= \'2018-05-02\' ;'

正如你所看到的,TSE-****都被认为是一个论点。我正在将字典传递给execute(),但是包含TSE-****值的命名参数的元组会导致错误,并且尝试使用已经在它们周围带有“'”的字符串也无法工作,因为它也会转义它们。我试过各种各样的东西,但都不走运。任何洞察都是值得赞赏的!

最佳答案

通过atuple展开IN列表:

sql = 'SELECT * FROM Compressor WHERE site_id IN %(sites)s'
cur.execute(sql, { 'sites': tuple(sites.keys()), })

关于python - 如何在字典内部使用元组为psycopg2中的命名参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50141689/

10-16 21:42