python - Python Mysql Insert - 元组索引超出范围
问题描述
这是我遇到问题的代码片段
for x in myresult:
sql = "INSERT INTO `writing_correction` (`autoinc`, `q_usage_id`, `ruleId`, `message`, `replacements`, `offset`, `errorLength`, `category`, `ruleIssueType`) VALUES (NULL, %d, %s, %s, %s, %d, %d, %s, %s )"
# sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
# sql = "INSERT INTO `writing_correction` (`autoinc`, `q_usage_id`, `ruleId`, `message`, `replacements`, `offset`, `errorLength`, `category`, `ruleIssueType`) VALUES (NULL, '100', 'ruleid', 'message', 'replacemenet', '12', '3', 'cat', 'ruleissuetype')"
# val = ("John", "Highway 21")
# mycursor.execute(sql, val)
print(x[3])
matches = tool.check(x[3])
for y in matches:
# sql = "INSERT INTO `writing_correction` (`autoinc`, `q_usage_id`, `ruleId`, `message`, `replacements`, `offset`, `errorLength`, `category`, `ruleIssueType`) VALUES (NULL, %d, %s, %s, %s, %d, %d, %s, %s )" % ( x[0], y.ruleId, y.message, y.replacements, y.offset , y.errorLength, y.category, y.ruleIssueType )
val = ( [ x[0] ], (y.ruleId), (y.message), (y.replacements), [y.offset] , [y.errorLength] , (y.category), (y.ruleIssueType) )
print(val)
# mycursor.execute(sql , ( x[0], y.ruleId, y.message, y.replacements, y.offset , y.errorLength, y.category, y.ruleIssueType ) )
mycursor.executemany(sql, val)
注释代码是我尝试使其工作的尝试和错误尝试,但由于某种原因它无法正常工作。
目前我收到以下错误:
File "/usr/local/lib/python3.8/dist-packages/mysql/connector/cursor.py", line 75, in __call__
return bytes(self.params[index])
IndexError: tuple index out of range
解决方案
val
应该是一个元组数组。每个元组对应一行。所以一次填写数组,然后executemany
一次。
所以:
val = []
for y in matches:
val.append( ( x[0], y.ruleId, y.message, y.replacements, y.offset , y.errorLength , y.category, y.ruleIssueType ) )
print(val)
mycursor.executemany(sql, val)
参考:executemany
推荐阅读
- javascript - d3-attrTween 与自定义函数。(我对补间函数有什么误解?)
- javascript - Excel Javascript API 是否仅用于创建加载项?
- mysql - SQL 查询以在加入时显示特定用户的文档
- python-3.x - Python(3.8.2) - 将 selenium(3.141.0) 网页元素特殊字符转换为字符串
- rest - 无状态数据同步 API 中的滚动与(从+大小)分页与 search_after
- filenet-p8 - FileNet 异常“读取 RenditionEngineConnection 期间发生异常”
- lua - 尝试在我的 lua 脚本中使用“require(”zip“)”,出现错误
- c++ - std::mbstate_t 的 Microsoft C++ 实现
- apache-flink - 是否可以用操作员状态模拟键控状态?
- python - 将pdf发布到api(python)返回编码错误的响应