我能够连接到我的数据库。但我想更改该特定列中存在的值。
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
最佳答案
正如我在评论中所说,您需要为查询指定列 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])))
关于python - 如何通过 python 修改 mysql 数据库中存在的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30644155/