2

I'm having a problem with trying to install a search function on my web application. The problem is with the following code. I've tried the following two queries but python gives me an error that I will list below:

def searchBox(user_id, searchparams):

try:
    cursor = connection.cursor()

    if cursor:
        sql = "SELECT * FROM db_email WHERE user_id = %d AND deleted = 0 AND subject LIKE '%%%s%%';"
        cursor.execute(sql % (user_id, searchparams)

I have also tried:

try:
    cursor = connection.cursor()

    if cursor:
        sql = "SELECT * FROM db_email WHERE user_id = %d AND deleted = 0 AND subject LIKE " + "'%" + searchparams + "%';"
        cursor.execute(sql % (user_id))

Both return this error for me:

TypeError: not enough arguments for format string

This is the only raw queries that I have had any trouble with and it's related to the way I need to call LIKE. I could write a stored procedure instead to bypass python but I feel like I'm doing something dumb and overlooking an issue. Any help would be appreciated


Thank you. I think a part of the problem is with my LIKE query I need my searchparams to be enclosed with percentage signs and the below answer doesn't work like so -

subject LIKE '%somestringimlookingfor%' 

with the code above it seems to come out to 'test'%''. Any ideas?

Dalbrecht
  • 23
  • 4

1 Answers1

3

Don not use string interpolation for SQL queries, it's completely unsafe.

Instead, use query parameters:

sql = """SELECT 
             * 
         FROM 
             db_email 
         WHERE
             user_id = %s AND 
             deleted = 0 AND 
             subject LIKE '%%%s%%'"""
cursor.execute(sql, (user_id, searchparams))

Percentage sign should be escaped with %.

UPD:

Slightly different option:

sql = """SELECT 
             * 
         FROM 
             db_email 
         WHERE
             user_id = %s AND 
             deleted = 0 AND 
             subject LIKE %s"""
cursor.execute(sql, (user_id, "%" + searchparams + "%"))

See also:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Thank you. I think a part of the problem is with my LIKE query I need my searchparams to be enclosed with percentage signs like so - subject LIKE '%somestringimlookingfor%' with the code above it seems to come out to 'test'%''. Any ideas? – Dalbrecht Sep 27 '13 at 13:27
  • @Dalbrecht please see `UPD` section in the answer. Let me know if it works for you. – alecxe Sep 29 '13 at 19:43