veera Mani
veera Mani

Reputation: 11

Why am I not able to update data in SQLite database from Python?

I am trying to update or rather modify the existing data in the particular cell of a SQLite database from Flask Python. But I can't update. Also I didn't receive any error while doing so. At the same time, I am able to insert a new data in the new row of the table.

Server side code:

@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)

Upvotes: 0

Views: 1446

Answers (1)

CL.
CL.

Reputation: 180060

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

This command updates all rows that have the value '1' in the id column. If nothing happens, then this implies that there is no such row.

If the id column contains numbers, then you must search for a number:

... WHERE id=1

And you should always use parameters to avoid formatting problems like this (and SQL injection attacks):

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

Upvotes: 3

Related Questions