简体   繁体   中英

How do I get a literal '%' in a mysql connector python query?

Consider this code:

def search(searchstr: str, limit: int=10, offset: int=0):
    csr = app.sql.cursor(dictionary=True)
    csr.execute("select username, fname, bio from followers where username like %%%s%% limit %d offset %d", (searchstr, limit, offset))
    return csr.fetchall()

search("j")

where app.sql is a reference to the connection object.

I would like it to execute something similiar to: select username, fname, bio from followers where username like %j% limit 10 offset 0 but instead it always gives me the error:

  File "/---/user.py", line 67, in search
    csr.execute("select username, fname, avatarUrl, bio from followers where username like %%%s%% limit %d offset %d", (searchstr, limit, offset))
  File "/---/venv/lib/python3.8/site-packages/mysql/connector/cursor.py", line 542, in execute
    raise errors.ProgrammingError(
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement

I can't figure out what I am doing wrong because

>>> "%%%s%% %d %d" % ("j", 10, 0)
"%j% 10 0"

which is the expected output. How can I fix this?

Placeholders do not work like copy and paste, you can't just place them anywhere and expect them to be understood. Even if it did work like that, in your case you'd end up with like %foo% , which is invalid SQL syntax.

You need to put one string placeholder into the query, and provide a string as argument which contains the LIKE wildcards:

csr.execute('... LIKE %s ...', (f'%{searchstr}%', ...))

In other words, you supply the % wildcards from Python, not from within the SQL statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM