PyODBC 迭代更新 - "Not a Query"



我正在从SQL Server 2008 R2表中提取客户服务票证的措辞("注意"),然后运行情绪分析,并使用该分析更新同一表中的"情绪"字段。以下是有关表格字段的更多信息:

TicketNoteID(PK, int, not null)
TicketID (FK, int, not null)
UserName (varchar(20), not null)
Note (varchar(max), not null)
Author (varchar(50), not null)
isExternal (bit, null)
DateTimeCreated (datetime, not null)
NoteID (int, null)
DateTimeUploaded (datetime, null)
Error (bit, null)
ErrorMessage (varchar(max), null)
Sentiment (float, null)

当我运行下面的代码时,我得到了这个错误:

pyodbc编程错误:没有结果。以前的SQL不是查询。

我已经根据其他关于这个错误的帖子对我的代码进行了建模,但我找不到任何能解决这个问题的东西。这是代码:

import pyodbc
from textblob import TextBlob
cnxn = pyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=...')
cur = cnxn.cursor()
sql = """
    SELECT Note
    FROM dbo.DSDTicketNotes
    where Sentiment is NULL
"""
rows = cur.execute(sql)
for row in rows:
    note = cur.fetchone()
    row = str(note)
    blob = TextBlob(row)
    sent = blob.sentiment.polarity
    sentUpdate = cur.execute("UPDATE dbo.DSDTicketNotes SET Sentiment = ?", sent)
cur.close()
cnxn.close()

我感谢任何帮助!

不可能同时迭代光标结果使用相同的光标执行其他语句。

如果要求逐个迭代SELECT结果(例如,结果太大而无法放入内存)并采取行动,请管理两个游标:

...
selectCur = cnxn.cursor()
updateCur = cnxn.cursor()
selectSQL = """
    SELECT TicketNoteID, Note
    FROM dbo.DSDTicketNotes
    where Sentiment is NULL
"""
updateSQL = """
    UPDATE dbo.DSDTicketNotes
    SET Sentiment = ?
    WHERE TicketNoteID = ?
"""
for row in selCur.execute(selectSQL):
    id = row[0]
    blob = TextBlob(str(row[1]))
    sent = blob.sentiment.polarity
    updateCur = updateCur.execute(updateSQL, (sent, id))
    updateCur.commit()
...

或者,如果SELECT结果集总是很小,则将结果拉到列表中进行迭代。这允许光标重用:

...
cur = cnxn.cursor()
selectSQL = """
    SELECT TicketNoteID, Note
    FROM dbo.DSDTicketNotes
    where Sentiment is NULL
"""
updateSQL = """
    UPDATE dbo.DSDTicketNotes
    SET Sentiment = ?
    WHERE TicketNoteID = ?
"""
rows = cur.execute(selectSQL).fetchall()
for row in rows:
    id = row[0]
    blob = TextBlob(str(row[1]))
    sent = blob.sentiment.polarity
    cur = cur.execute(updateSQL, (sent, id))
    cur.commit()
...

不管使用哪种方法,您都希望在SELECT中包含主键,以便它可以用于UPDATE正在处理的特定行。

最新更新