Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape the % and \ signs in pymysql using LIKE clause?

I want to find something like "probability: 10%" or "10% high" in my 'events' column, but when I used the code below:

conn = pymysql.connect(host="localhost", port=3306, user='myid', passwd='mypwd', db='mydb', charset='utf8')
curs = conn.cursor()

key = "%"
curs.execute(
        "SELECT count(*) AS number FROM city WHERE events LIKE %s",
        ("%" + key + "%",)
    )

it returned every row in the table. It executed this query:

  SELECT count(*) AS number FROM city WHERE events LIKE '%%%'

like this, which I didn't intend.

Searching for the backslash sign also gave me incorrect results.

What should I do to get the correct result?

Thanks in advance.

like image 200
Park Avatar asked May 12 '19 07:05

Park


People also ask

What is cursor in PyMySQL?

class pymysql.cursors. Cursor (connection) This is the object used to interact with the database. Do not create an instance of a Cursor yourself. Call connections.

What does PyMySQL fetchAll return?

PyMySQL fetchAll The fetchAll method retrieves all (remaining) rows of a query result, returning them as a sequence of sequences. In the example, we retrieve all cities from the database table. This SQL statement selects all data from the cities table.


Video Answer


2 Answers

instead of the concat the wildchar in param you could use concat in SQL and pass the value

 curs.execute(
    "SELECT count(*) AS number FROM city WHERE events LIKE CONCAT('%', %s, '%')",
     (key ,)
) 

or as uggested by @Notinlist

curs.execute( "SELECT count(*) AS number FROM city WHERE events LIKE CONCAT('%%', %s, '%%')", (key ,) )

like image 90
ScaisEdge Avatar answered Oct 07 '22 05:10

ScaisEdge


You ought to use SQL ESCAPE clause:

curs.execute(
    "SELECT count(*) AS number FROM city WHERE events LIKE '%#%%' ESCAPE '#'"
)
like image 30
reartnew Avatar answered Oct 07 '22 05:10

reartnew