python - 如何通过 python 修改 mysql 数据库中存在的列?

标签 python mysql

我能够连接到我的数据库。但我想更改该特定列中存在的值。

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/

相关文章:

javascript - 按日期对两个表进行排序并在 html <table> 中显示输出

java - 每次在数据库中创建新条目时添加 ListView

字典的python理解循环

python - 在 PIL 中打开图像文件时出错

python - 如何在Tensorflow中为张量的所有初始化权重添加一个常量?

mysql - 选择特定值作为存储过程中的列

php - 产品销售报告 每周 每月

php - 当有其他占位符时,如何在 IN() 子句中使用占位符?

Python:在此示例中抛出异常是正确的用例吗?

python - 如何在数据框中创建一个新列,它是另一列和条件的函数,比 for 循环更快?