Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 468
Risino Avatar asked Oct 20 '10 12:10

Risino


People also ask

How do you remove a record from a table?

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.

How do you delete a record from a table in SQL?

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.


2 Answers

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.

like image 58
Cameron Gagnon Avatar answered Sep 30 '22 06:09

Cameron Gagnon


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.

like image 35
Dregnox Avatar answered Sep 30 '22 06:09

Dregnox