3

I use PyMySQL to query from a MySQL database in python:

filter = "Pe"
connection = pymysql.connect(host="X", user="X", password="X", db="X", port=3306, cursorclass=pymysql.cursors.SSCursor)
cursor = connection.cursor()
sqlquery = "SELECT * FROM usertable WHERE name LIKE '%%s%'"
cursor.execute(sql, (filter))
response = cursor.fetchall()
connection.close()

This returns nothing. I could write:

sqlquery = "SELECT * FROM usertable WHERE name LIKE '%" + filter +"%'"

and execute: cursor.execute(sql), but then I lose the escaping, which makes the program vulnerable for injection attacks, right?

Is there way I could insert the value into the LIKE without losing the escape?

...WHERE name LIKE '%%%s%%'" does not work. I think %s adds ' on both sides of the replaced escaped string as a part of its function within PyMySQL.

Brakebusk
  • 45
  • 1
  • 5

2 Answers2

2

You need to pass the whole pattern as a query parameter, and use a tuple:

filter = "%Pe%"
sql = "SELECT * FROM usertable WHERE name LIKE %s"
cursor.execute(sql, (filter,))
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
0

Double the % you want to keep.

sqlquery = "SELECT * FROM usertable WHERE name LIKE '%%%s%%'"
AdrienW
  • 3,092
  • 6
  • 29
  • 59
  • Does not work. I think %s adds ' on both sides of the replaced escaped string as a part of its function within PyMySQL. – Brakebusk Jul 28 '16 at 12:14