【问题标题】:Format string with multiple parameters so that MySQL can proces them使用多个参数格式化字符串,以便 MySQL 可以处理它们
【发布时间】:2020-04-30 11:52:06
【问题描述】:

我想知道如何格式化 API 返回的字符串,以便 Mysql 可以处理它。

这是我的 API 返回的字符串:bad_string = "History,Romance,Business & Money"

尝试 1:

cursor.execute("SELECT * FROM book WHERE scrape_category IN (%s) ORDER BY RAND() LIMIT 15", bad_string)

返回此消息:

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

尝试 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)

返回此消息:

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

这行得通:

cursor.execute("SELECT * FROM book WHERE scrape_category IN ('Romance', 'History', 'Business & Money') ORDER BY RAND() LIMIT 15")

当我这样做时查询有效:

cursor.execute("SELECT * FROM book WHERE scrape_category IN ('Romance', 'History', 'Business & Money') ORDER BY RAND() LIMIT 15")

如何格式化字符串并让 MySQL 返回结果?

【问题讨论】:

  • 我应该更明确一点:您需要bad_string 拆分为单独的值。最好在表单中执行此操作,然后将其发送到 Flask 视图。看看MultiDict.getlist() method,如果你多次使用同一个参数名,你可以得到一个列表,例如使用/preferred_categories?categories=Romance&amp;categories=History&amp;categories&amp;Business%20%26%20Money 调用您的视图,然后使用categories = request.args.getlist('categories')

标签: python mysql string where-in


【解决方案1】:

试试这样的:

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)

【讨论】:

  • 这很好用!非常感谢!你成就了我的一天:D
【解决方案2】:

您的字符串值为: "History,Romance,Business &amp; Money"

你需要这个:'Romance', 'History', 'Business &amp; Money'

尝试类似bad_string = " 'Romance', 'History', 'Business &amp; Money' "

希望对你有帮助...

【讨论】:

    猜你喜欢
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多