【问题标题】:MYSQL:: Connector/Python UPDATE statement with special chars doesn't workMYSQL:: 带有特殊字符的连接器/Python UPDATE 语句不起作用
【发布时间】:2018-12-23 20:11:55
【问题描述】:

我正在尝试使用 Selenium 和 Beautifulsoup 抓取网页,然后将结果存储到 MySQL。 结果包含许多特殊字符,例如 ; ' " =.. (因为它正在解析 HTML)

我关注了这个mysql connector/python 并且 INSERT 工作正常,但是 UPDATE。
如果我选择我的表,我可以看到类似这样的内容

<div style="width:80px; float: ~~~ ... </div>

表示目标 HTML 元素存储成功。 这是我的插入和更新。

# after import and configs
soup = BeautifulSoup(innerHTML, "html.parser")
text = soup.prettify()
print(text)

# this INSERT works fine
# insert = ("INSERT INTO g_cache (a_col, cache_contents) VALUES(%s, %s)")
# data_row = ('aaa', text)
# cursor.execute(insert, data_row)

# Trying to UPDATE already inserted row. Not working
# I executed and commented above INSERT before run the following UPDATE
update = ("""UPDATE g_cache SET cache_contents =%s WHERE id=21""")
data_col = (text)
cursor.execute(update, data_col)

# If I use one complete string, it works though. For example
# cursor.execute("""UPDATE g_cache SET cache_contents ='111' WHERE id=21""")
cnx.commit()

错误消息是
mysql.connector.errors.ProgrammingError: 1064 (42000): 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 '%s WHERE id=21' 附近使用正确的语法

我刚刚关注了 MYSQL::Connector/Python API。
我不明白为什么 INSERT 有效,但 UPDATE 无效,使用相同的字符串。
有人知道吗?

【问题讨论】:

  • 试试data_col = (text,)。 Afaik,参数必须作为元组传递,变量后面的逗号在这里很重要。
  • 哦,它可以与逗号一起使用,谢谢!你应该把它写成答案,所以我可以选择。

标签: python mysql python-3.x selenium-webdriver mysql-connector


【解决方案1】:

参数必须作为映射(即dict)或作为元组传递。仅传递一个参数时省略尾随逗号会导致它被视为标量,因此必须像这样传递参数:

data_col = (text,)

The docs 也在显着的注释中提及这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 2019-07-12
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多