Python Mysql插入元组索引超出范围

2024-09-30 22:10:07 发布

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

下面是我遇到问题的代码片段

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

Tags: inmessagesqlvaloffsetinsertvaluescategory
1条回答
网友
1楼 · 发布于 2024-09-30 22:10:07

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

相关问题 更多 >