2016-06-09 157 views
0

我試圖插入一個列表通過psycopg2的SQL查詢,但每次看時間是'雙打吧...Psycopg2 Python中插入列表

繼承人的代碼:

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

謝謝!

+0

不過這個名單是2964長,將改變每次我做了查詢..我該怎麼解決? – MathLal

回答

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),)) 

BTW在默認情況下另一方面Python列表轉換爲Postgres的ARRAY

+0

它的工作!謝謝 – MathLal