I have a problem with deleting a record from my SQLite3 database:
conn = sqlite3.connect('databaza.db')
c = conn.cursor()
data3 = str(input('Please enter name: '))
mydata = c.execute('DELETE FROM Zoznam WHERE Name=?', (data3,))
conn.commit()
c.close
Everything is OK, no errors, but the delete function doesn't work!
Does anyone have an idea?
The SQL DELETE Query is used to delete the existing records from a table. You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted.
DELETE SyntaxDELETE FROM table_name WHERE condition; Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted.
The correct syntax for a parameterized query is:
mydata = c.execute("DELETE FROM Zoznam WHERE Name=?", (data3,))
Make sure the parameter uses the comma, to make it a python tuple.
This will help prevent SQL Injection which is possible when passing in a formatted string. More on SQL Injection here
Related post here.
I'm a little late to the party but if you Google search "python sqlite delete row" This is the first thing that comes up and I was having the same issue where things were not getting DELETE'd from my sqlite DB. I'm using Python 2.7 on Debian Jessie.
Previously, when I wrote Python code for adding and retrieving information in the sqlite database, I had written the commands with correct capitalization where needed and it worked.
curs.execute("SELECT example_column1 FROM example_table WHERE example_column2=(?)", (Variable,))
However...
curs.execute("DELETE FROM example_table WHERE example_column1=(?)", (Variable,)):
This for some reason does not work with the DELETE command. I had to send that command in all lower-case before sqlite would respect the command being sent.
conn=sqlite3.connect('example.db')
curs=conn.cursor()
curs.execute("delete from example_table where example_column=(?)", (Variable,))
conn.commit()
conn.close()
I have no idea why. I tried all the previously mentioned methods but having the command sent in lowercase was the only way I could get it to work. Hope this helps any struggling neophytes in their journey into Python and sqlite.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With