Solved

Python MySQLdb parametrized query

Posted on 2014-03-30
1
578 Views
Last Modified: 2014-03-30
Hi everybody!

I need to write a parametrized mysql query with python using MySQLdb

I did this successfully:

cursor.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))

The problem comes when I want to do a LIKE with two parameters:

cursor.execute("SELECT * FROM foo WHERE bar like '%%s%' AND baz like '%%s%'", (param1, param2))

I get an error:

    query = query % db.literal(args)
ValueError: unsupported format character ''' (0x27) at index 47


How can I write this correctly?
0
Comment
Question by:ltpitt
1 Comment
 
LVL 1

Accepted Solution

by:
ltpitt earned 0 total points
ID: 39965516
Here's how :)

cursor.execute("SELECT * FROM data WHERE params LIKE %s LIMIT 1", ("%" + param + "%",))
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question