【问题标题】:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'keyword")\'您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获得在 \'keyword")\' 附近使用的正确语法
【发布时间】:2020-05-11 19:35:59
【问题描述】:

    url = 'test.com///"asdasdasd'
    name = "test"
    formatURL = url.replace("//","/")
    print(formatURL)

    conn= db.cursor()
    conn.execute("Insert Into website (URL,NAME) VALUES("{}","{}")".format(url,name))
    data_base.commit()

很可能,替换操作未正确完成,我收到以下错误。

输出:

> test.com//"asdasdasd 
> pymysql.err.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'test")\' at line 1')

如何将所有“//”字符转换为“/”字符?

【问题讨论】:

  • 不要格式化 sql 字符串的值:使用参数化查询conn.execute("Insert Into website (URL,NAME) VALUES( %s, %s)", (url,name))
  • 哦,替换已正确完成。正如 Patrick 指出的那样,您只是遇到了 SQL 注入错误。
  • 这个解决方案能解决这个问题吗?那么它是一个永久的解决方案吗?它是否适用于不同的 SQL 注入?
  • 必须是肯定的——你的字符串使用 " 来分隔自己并且你在 {} 之前/之后使用 " ,所以 python 对什么是字符串以及什么代码和什么不是很困惑。并且它只是将参数传递给 sql 的方法 - 你永远不要使用格式来给出值。
  • 您应该从该行收到 Python 语法错误。

标签: python mysql python-3.x


【解决方案1】:

您弄乱了字符串的分隔符。不要使用str.format()将参数格式化为sql字符串,使用参数化查询:

conn.execute("Insert Into website (URL,NAME) VALUES( %s, %s)", (url,name))

这里是混乱:

conn.execute("Insert Into website (URL,NAME) VALUES(" {} "," {} ")".format(url,name))
              111111111111111111111111111111111111111    222    333
                                         unrelated    {}     {}

所有1 都是一个字符串,所有2 都是另一个字符串,所有3 都是第三个字符串。 {} 都是不相关的大括号(?),.format(url,name) 仅适用于不是有效格式字符串的")"(又名3)。

只需使用参数化查询 - 它们更安全、更容易:

来源:https://xkcd.com/327/ (License)

以及许多语言的语法提示:https://bobby-tables.com/python

【讨论】:

    猜你喜欢
    • 2011-08-07
    • 2012-05-02
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多