Python MySQL 更新

Python Update in MySQL

我一直在努力让这个非常简单的查询在 Python 中实际工作。我是一个完整的 python 新手,字符串的处理方式似乎与我习惯的方式有很大不同。

我正在尝试的查询...

cur = db.cursor()
cur.execute("SELECT bluetooth_Id FROM student_Data")
data = cur.fetchall()


for row in data :
    bluetoothId=row[0]
    result=bluetooth.lookup_name(bluetoothId,timeout=5)
    print(result)
    if(result != None):
        cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s",(bluetoothId))
        print("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s",(bluetoothId))

问题似乎是我的实际 SQL 查询格式不正确。我知道这是因为最后一个打印语句 returns this

('UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s', 'th:is:is:my:bt:id')

当然那个 id 实际上不是它的 id returns...我不想把它给你 :)

我正在按照示例进行操作,但没有取得任何进展。我的蓝牙已打开,程序看到我的蓝牙 ID,它处理我的 mysql [=47= 中已有的 ID 列表],但它没有更新任何记录。

而且我确实检查过以确保我在 mysql table 中正确输入了我的 ID,所以这也不是问题所在!

更新

我能够获得使用此创建的正确 MySQL 查询:

cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id = '%s"%(bluetoothId)+"'")

这创造了

UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id = '11:11:11:11:11:11'

但是 MySQL table 仍然没有正确更新..我必须看看为什么会这样...

您需要这样做:

cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s"%(bluetoothId))

如果要进行替换,则需要 % 而不是逗号

解决方案是这样的:

cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id = '%s"%(bluetoothId)+"'")

然后我不得不添加

db.commit()

执行后,为了真正提交对 MySQL table 的更改。

感谢大家的帮助:)

Python mySQL Update, Working but not updating table