'How to delete a record from table?

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?



Solution 1:[1]

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.

Solution 2:[2]

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.

Solution 3:[3]

Try with:

mydata = c.execute('DELETE FROM Zoznam WHERE Name = (?)', (data3))

Without the ',' and the '?' between '()'

Solution 4:[4]

I'm using Python 3.9 on windows.

c.execute("DELETE FROM Zoznam WHERE Name={0}".format(data3))
conn.commit()

Solution 5:[5]

I advise you to first make a string for the query , and then execute it. ex:

query = "delete from zoznam where name = '%s' " % data3
c.execute(query)
conn.commit() 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kelton Temby
Solution 2 Dregnox
Solution 3 Francisco de Larrañaga
Solution 4 kourosh
Solution 5 Gaurav Dave