为什么我无法从Python更新SQLite数据库中的数据?

时间:2017-04-25 08:07:24

标签: python sqlite

我正在尝试从Flask Python更新或更改修SQLite数据库的特定单元格中的现有数据。但我无法更新。这样做时我也没有收到任何错误。同时,我能够在表格的新行中插入新数据。

服务器端代码:

@app.route("/")
@app.route("/<state>")
def get_post_javascript_data(state=None):
        connection = sqlite3.connect('/home/pi/toggle7.db')
        cursor = connection.cursor()
        load = 'light5'
        status = 'ON'
        if state == 'Load1on':
                sock.send('Load1ON')
                print ("sent: Load1ON")
                try:
                     cursor.execute("UPDATE user1 SET load = 'light5' WHERE id='1'")
                     connection.commit()
                     message = "success"
                except:
                     connection.rollback()
                     message = "failure"
                finally:
                     connection.close()
                     print (message)

1 个答案:

答案 0 :(得分:2)

UPDATE user1 SET load = 'light5' WHERE id='1'

此命令将更新'1'列中值id的所有行。 如果没有任何反应,那么这意味着没有这样的行。

如果id列包含数字,则必须搜索数字:

... WHERE id=1

并且您应该始终使用参数来避免格式​​化问题(以及SQL注入攻击):

cursor.execute('UPDATE user1 SET load = ? WHERE id = ?', ['light5', 1])