0

I know how to use MySQL pattern matching, for example:

SELECT * FROM table WHERE col LIKE '%mid%'

I also know how to bind parameters into a sql query in python, for example:

import MySQLdb
s = 'something'
db = MySQLdb.connect(host=blablabla...)
cur = db.cursor()
sql = "SELECT * FROM table WHERE col = %s"
cur.execute(sql, s)
data = cur.fetchall()
db.close()

But I can't find a method to combine these together in one query, like

sql = "SELECT * FROM table WHERE col LIKE '%%s%'"
cur.execute(sql, s)

where the first and the third '%' are pattern character and the middle '%s' is used to bind parameter s. Anyone have an idea?

4
  • 1
    sql = "SELECT * FROM table WHERE col = %s" %some_words before call.. Commented Mar 11, 2016 at 7:13
  • @dsgdfg oh yes, that works! Thank you very much! Commented Mar 11, 2016 at 7:19
  • @XiangZhang: But don't use that because it's vulnerable to SQL injection! Commented Mar 11, 2016 at 7:26
  • @Eric Yes, I realized that. Thanks for reminding! Commented Mar 11, 2016 at 7:28

3 Answers 3

2

Alright, I will answer myself.. @dsgdfg inspired me and here is my code:

sql = "SELECT * FROM table WHERE col LIKE %s"
cur.execute(sql, "%"+s+"%")
Sign up to request clarification or add additional context in comments.

3 Comments

This is better than @dsgdfg's answer because you're leaving the interpolation to the database driver, which should protect you from injection
Yes, but still looking for better solution. I think this method is not that beautiful
Thnx for warning. deleted answer @Eric
0
sql = "SELECT * FROM table WHERE col LIKE CONCAT('%', %s, '%')"
cur.execute(sql, s)

(I am assuming that execute deals with escaping, thereby preventing SQL injection.)

Comments

0

for the people using py charm you can do this

qq=input("enter the author name:")
print(pd.read_sql_query("select Book_Id,Book_Name,book_author from bookd where book_author like '%s'" %("%"+qq+"%",), conn2))
                

enter image description here

Comments

Your Answer

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.