我能够连接我的数据库。但我想更改该特定列中的值。
cursor.execute("SELECT * FROM foo;")
rows = cursor.fetchall()
for row in rows:
print(row)
上述代码的输出是,
('foo,bar,foo,bar',)
('foobar,bar',)
('foo,bar,buz,buz',)
我可以用
替换值rows = cursor.fetchall()
for row in rows:
print(re.sub(r'^[^,]*,', '', row[0]))
cursor.close()
返回,
bar,foo,bar
bar
bar,buz,buz
但我不知道如何将更改后的字符串设置为该特定列。
我想我需要使用update
查询,所以我尝试了
for row in rows:
cursor.execute("UPDATE foo SET categories=%s;", re.sub(r'^[^,]*,', '', row[0]))
但它返回错误消息
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1
答案 0 :(得分:1)
正如我在评论中所说,您需要为查询指定列ID:
for row in rows:
sub=re.sub(r'^[^,]*,', '', row[0])
cursor.execute("UPDATE drug_specifications SET categories=%s where id=%s;",(sub, str(row[0])))