您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,了解使用“关键字”)\”附近的正确语法

2024-06-26 14:01:35 发布

您现在位置:Python中文网/ 问答频道 /正文


    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')

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


Tags: thetonametestcomurldbyour
1条回答
网友
1楼 · 发布于 2024-06-26 14:01:35

你弄乱了字符串的分隔符。不要使用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)仅应用于")"(aka 3),这不是有效的格式字符串

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

资料来源:https://xkcd.com/327/License

https://xkcd.com/327/

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

相关问题 更多 >