Loop中的INSERT并不像我期望的那样工作(Python 2.7)

时间:2017-06-23 06:27:16

标签: python mysql loops insert

我正在对一张有3条记录的表进行情绪分析(图1)。当我将结果打印到屏幕时,我的代码(图2)似乎工作正常(图3)。对于3行中的每一行,我返回3个值 - 行ID,情感分数和幅度分数。 (9结果):

但是,当我尝试将相同的9个值插入表中时(图4),只有3个值(来自第一行)插入到我的表中。

我觉得这很明显,但我对这个问题感到困惑。任何人都可以指出什么阻止插入工作循环的所有3次迭代。

编码新手。

图1。

enter image description here

图2。

import mysql.connector
from google.cloud import language
cnx = mysql.connector.connect(user='Blah', password='Blah',
                          host='Blah',
                          database='Blah')

cursor = cnx.cursor(buffered=True)

Latest = ("SELECT ResID, TextResp FROM Response")

client = language.Client()

cursor.execute(Latest)
for row in cursor:
    document = client.document_from_text(row[1])
    sent_analysis = document.analyze_sentiment()
    sentiment = sent_analysis.sentiment
    annotations = document.annotate_text(include_sentiment=True, include_syntax=True, include_entities=True)
    ResID_ =row[0]
    PhraseSent_ = sentiment.score
    PhraseMag_ = sentiment.magnitude

    print(ResID_)
    print(PhraseSent_)
    print(PhraseMag_)

cnx.commit()
cursor.close()
cnx.close()

图3。

Fig 2

图4.使用INSERT语句的循环没有按预期工作

enter image description here

1 个答案:

答案 0 :(得分:0)

问题是正在迭代的游标只保存表中的第一行而不是所有3行。改变

  

表示游标中的行:

  

表示cursor.fetchall()中的行:

解决了问题