Psycopg2 Python插入列表

时间:2016-06-09 20:21:44

标签: python sql postgresql psycopg2

我正在尝试通过psycopg2将一个列表插入到SQL查询中,但每次看到它都是'它会加倍...

继承人代码:

for Line in ListFile:
    if CountLigne == 1:
        IDList = "'" + (Line[1].replace('"', '')) + "', "
        CountLigne += 1
    elif CountLigne < NbrLigne:
        IDList += "'" + (Line[1].replace('"', '')) + "', "
        CountLigne += 1
    else:
        IDList += (Line[1].replace('"', '') + "'")

    break
print(IDList)
print(type(IDList))
FTDSQL = (
'''WITH ftd AS (
    SELECT m.event_user, m.event_ts, m.revenue, rank() OVER (PARTITION BY            m.event_user ORDER BY m.event_ts) as order_purchase
    FROM agg_monetization m
    WHERE revenue is not null
)
SELECT distinct ftd.event_user, SUM(ftd.revenue)
FROM ftd
WHERE order_purchase = 1
AND ftd.event_user IN (%s)
GROUP BY ftd.event_user, ftd.event_ts
'''
)
Cursor.execute(FTDSQL, [IDList])
print(Cursor.query)

清单:'849cf768-41ea-4ed0-9861-779369d3eede','10ad8dca-b4e6-4be5-93d3-b7fb88b1668a'

结果:AND ftd.event_user IN(''''849cf768-41ea-4ed0-9861-779369d3eede'',''10ad8dca-b4e6-4be5-93d3-b7fb88b1668a'',''863c3eaf-d98d-4f6a-bb97 -8756750e7a09 ''

谢谢!

1 个答案:

答案 0 :(得分:0)

Pyscopg2自动将元组转换为sql列表。看看Adaptation of Python values to SQL types。所以你只需要将列表更改为元组然后传递它。

FTDSQL = '''
  WITH ftd AS (
    SELECT 
      m.event_user, m.event_ts, m.revenue, 
      rank() OVER (PARTITION BY m.event_user ORDER BY m.event_ts) as order_purchase
    FROM agg_monetization m
    WHERE revenue is not null
  )
  SELECT
    distinct ftd.event_user, SUM(ftd.revenue)
  FROM ftd
  WHERE
    order_purchase = 1
  AND
    ftd.event_user IN %s
    -- parenthesis should be added automatically 
  GROUP BY ftd.event_user, ftd.event_ts
'''
)
Cursor.execute(FTDSQL, (tuple(IDList),))
另一方面,顺便说一下,Python列表默认转换为postgres ARRAY