使用Python在Postgres中参数化查询

问题描述:

我在使用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']) 

逃离%字符与一个更%

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

是从sql注入安全吗? – StillLearningToCode

+0

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