我想在 python 中使用单个查询更新多行。我使用 executemany 基于以下 example但我得到了这个错误:
Operand should contain 1 column(s)
这是我的代码,显示了我如何创建需要更新的行的值列表。我更新了其发布只是字符串 NULL 的行。
def UpdatePostingList (self, data):
queryUpdate='Update KeywordIndex2 set postings=%s where keyValue= %s'
querySelect='SELECT postings FROM KeywordIndex2 where keyValue= %s'
list=[]
try:
for i in range(0,len(data)):
keyValue=data[i][0]
k=(keyValue,)
self.cursor.execute(querySelect,k)
postings= self.cursor.fetchall()
pst=[x[0] for x in postings]
if pst[0]=='NULL':
p=data[i][1]
list.insert(i, (p,keyValue))
print list
self.cursor.executemany(queryUpdate,list)
self.connection.commit()
except MySQLdb.Error, e:
try:
print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
except IndexError:
print "MySQL IndexError: %s" % str(e)
self.connection.rollback()
我得到了这个输出:
[([(3, 0.4698370099067688), (12, 0.38598471879959106), (2, 0.33203423023223877), (1, 0.3257867097854614), (8, 0.3251670002937317)], 'york'), ([(21, 0.5803983509540558), (18, 0.5671890079975128), (24, 0.5287801623344421), (9, 0.5264906287193298), (15, 0.47776609659194946)], 'yang'), ([(12, 0.6617408990859985), (3, 0.6475195586681366), (15, 0.4491569995880127), (24, 0.4268345832824707), (21, 0.40550071001052856)], 'world')] MySQL Error [1241]: Operand should contain 1 column(s)
为了明确列表的最后一个成员,keyValue 是 world 而 postinglist 是元组的第一部分。
最佳答案
我的代码的问题是我将 p 作为 postings 列的元组列表发送。我在下面的代码行中将 p 更改为 str(p) ,问题就解决了。
list.insert(i, (str(p),keyValue))
关于python - 如何解决 Operand should contain 1 column(s) for update multiple rows in python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41779537/