1

I am having a bit of trouble parameterizing a sql query with python. Don't exactly know why this error is happening... if the tuple has two members and i am using two parameters in the sql, how am i getting an off by one error?

error message:

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

calling function in main:

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

method in class User:

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'])
asked Aug 11, 2016 at 20:08

1 Answer 1

1

Escape the % characters with one more %

and c.cust_name ilike '%%_bar'
and c.baz not ilike 'test%%' """
answered Aug 11, 2016 at 20:35
Sign up to request clarification or add additional context in comments.

1 Comment

is that safe from sql injection?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.