mysql - MySQL 更新的 Python 格式字符串
问题描述
由于某些 NLP 需求,我是一名长期的 Perl 程序员,试图学习 Python。所以这可能是一个愚蠢的菜鸟问题。
我正在尝试从 MySQL 获取文本,使用 spaCy 将实体类型计数到字典中,然后使用字典的 JSON 版本更新数据库记录。一切都很好,直到我到达最后一步。代码是:
import spacy
nlp = spacy.load("en_core_web_sm")
import json
import mysql.connector
mydb = mysql.connector.connect(
[redacted]
)
mycursor = mydb.cursor()
nrows = mycursor.execute("select id,message from post where entities is null")
while True:
row = mycursor.fetchone()
ne_types = {}
if row == None:
break
doc = nlp(row[1])
for ent in doc.ents:
if ent.label_ not in ne_types:
ne_types[ent.label_] = 0
ne_types[ent.label_] += 1
sql = "update post set entities = '",json.dumps(ne_types),"' where id = ",row[0]
mycursor.execute(sql)
mydb.commit()
当我在 mycursor.execute 语句处中断时,我的调试器说 sql 是一个元组。嗯,这听起来不对。当我尝试执行时出现错误
Traceback (most recent call last):
File "C:\named-ent.py", line 29, in <module>
mycursor.execute(sql)
File "c:\python36\lib\site-packages\mysql\connector\cursor_cext.py", line 234, in execute
self._cnx.handle_unread_result()
File "c:\python36\lib\site-packages\mysql\connector\connection_cext.py", line 712, in handle_unread_result
raise errors.InternalError("Unread result found")
mysql.connector.errors.InternalError: Unread result found
所以这确实是不对的(虽然我不能理解那个错误信息)。如何正确构造 sql 字符串?
更新我尝试了尼克的建议来更改代码,如下所示:
mycursor.execute("update post set entities = %s where id = %s", (json.dumps(ne_types), row[0]))
并且仍然出现错误:
Traceback (most recent call last):
File "C:\named-ent.py", line 28, in <module>
mycursor.execute("update post set entities = %s where id = %s", (json.dumps(ne_types), row[0]))
File "c:\python36\lib\site-packages\mysql\connector\cursor_cext.py", line 234, in execute
self._cnx.handle_unread_result()
File "c:\python36\lib\site-packages\mysql\connector\connection_cext.py", line 712, in handle_unread_result
raise errors.InternalError("Unread result found")
mysql.connector.errors.InternalError: Unread result found
解决方案
推荐阅读
- javascript - 在视口中运行 CSS 关键帧动画
- r - 将距离线添加到 ggplot2
- javascript - 在检查浏览器中隐藏 html 属性
- ios - 使用 NavigationView 和 List 时如何更改 SwiftUI 中的背景颜色?
- reactjs - 如何放弃 switch case 以支持多态 React?
- javascript - Correctly escaping ° character from C# to javascript
- flutter - How to remove overscroll on ios?
- php - PHP 登录表单不显示警告框
- javascript - 如何在胜利图中将渐变填充到 x 轴
- php - preg_match 而关键字附加到其他东西