2016-08-11 58 views
1

我在使用python參數化SQL查詢時遇到了一些麻煩。不完全知道爲什麼這個錯誤發生......如果元組有兩個成員,我在sql中使用兩個參數,我如何得到一個錯誤?使用Python在Postgres中參數化查詢

錯誤消息:

File "...\app.py", line 27, in main 
rows = User.daily_users_by_pool_name('2016-08-01', '2016-08-02') 
File "...\user.py", line 48, in daily_users_by_pool_name 
cursor.execute(query, (start_date, end_date)) 
IndexError: tuple index out of range 

在主調用函數:

rows = User.daily_users_by_pool_name('2016-08-01', '2016-08-02') 

類用戶方法:

from database import ConnectionFromPool 
from datetime import datetime 
import pandas as pd 
import numpy as np 
import psycopg2 
... 

@classmethod #static 
def daily_users_by_pool_name(cls, start_date, end_date): 
    '''returns a Pandas.DataFrame of results''' 

    query = """ 
      Select foo.dos::date, foo.cust_id 
      from foo f 
      join customer c on f.id = c.id 
      where foo.dos >= %s::DATE 
       and foo.dos < %s::DATE 
       and c.cust_name ilike '%_bar' 
       and c.baz not ilike 'test%' """ 


    with ConnectionFromPool() as cursor: 
     cursor.execute(query, (start_date, end_date)) 

     return pd.DataFrame(cursor.fetchall(), columns=['foo', 'cust_id']) 

回答

1

逃離%字符與一個更%

and c.cust_name ilike '%%_bar' 
and c.baz not ilike 'test%%' """ 
+0

是從sql注入安全嗎? – StillLearningToCode

+0

@StillLearningToCode我不明白如何允許SQL注入... –