问题
I want to know how I can format a string that is returned by the API so that Mysql can process it.
This is the string my API returns: bad_string = "History,Romance,Business & Money"
Attempt 1:
cursor.execute("SELECT * FROM book WHERE scrape_category IN (%s) ORDER BY RAND() LIMIT 15", bad_string)
Returns this message:
Traceback (most recent call last):
File "C:\PATH", line 23, in <module>
cursor.execute("SELECT * FROM book WHERE scrape_category IN (%s) ORDER BY RAND() LIMIT 15", bad_string)
File "C:\PATH\AppData\Roaming\Python\Python37\site-packages\mysql\connector\cursor_cext.py", line 259, in execute
"Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
Attempt 2:
bad_string_2 = "'Romance', 'History', 'Business & Money'"
cursor.execute("SELECT * FROM book WHERE scrape_category IN (%s) ORDER BY RAND() LIMIT 15", bad_string_2)
Returns this message:
Traceback (most recent call last):
File "C:PATH", line 21, in <module>
cursor.execute("SELECT * FROM book WHERE scrape_category IN (%s) ORDER BY RAND() LIMIT 15", bad_string_2)
File "C:\PATH\AppData\Roaming\Python\Python37\site-packages\mysql\connector\cursor_cext.py", line 246, in execute
prepared = self._cnx.prepare_for_mysql(params)
File "C:\PATH\AppData\Roaming\Python\Python37\site-packages\mysql\connector\connection_cext.py", line 520, in prepare_for_mysql
raise ValueError("Could not process parameters")
ValueError: Could not process parameters
This works:
cursor.execute("SELECT * FROM book WHERE scrape_category IN ('Romance', 'History', 'Business & Money') ORDER BY RAND() LIMIT 15")
The query works when i do this:
cursor.execute("SELECT * FROM book WHERE scrape_category IN ('Romance', 'History', 'Business & Money') ORDER BY RAND() LIMIT 15")
How do I format the string and make MySQL return results?
回答1:
Try with some like this :
filter ="History,Romance,Business & Money".split(',')
sqlcommand = "SELECT * FROM book WHERE scrape_category IN ({0})".format(
', '.join(['%s'] * len(filter)))
print(sqlcommand)
cursor.execute(sqlcommand, filter)
回答2:
Your string value is:
"History,Romance,Business & Money"
and you need this: 'Romance', 'History', 'Business & Money'
try something like bad_string = " 'Romance', 'History', 'Business & Money' "
Hope it helps...
来源:https://stackoverflow.com/questions/59722180/format-string-with-multiple-parameters-so-that-mysql-can-proces-them