Python SQLite Delete

by Atakan

Hello,
There are 2 different ways for SQLite delete operation, actually 2 sides are very similar to each other.
The difference is that we can delete one by one for the given id value.
The other is useful when we want to delete multiple ids.

For singular

def delete_my_contact_single(id):
    query = "DELETE from contact_table WHERE id = ?"
    cursor.execute(query, (id,))
    conn.commit()

delete_contact_single(1)

For multiple

def delete_my_contact_multiple(ids):
    query = "DELETE from contact_table WHERE id = ?"
    cursor.executemany(query, ids)
    conn.commit()

delete_contact_multiple([(15,),(16,)])

Full code of

delete.py
import sqlite3

conn = None
cursor = None


def init_connections():
    global conn
    global cursor
    conn = sqlite3.connect("contact_list.db")
    cursor = conn.cursor()

def close_connecton():
    cursor.close()
    conn.close()


def delete_my_contact_single(id):
    query = "DELETE from contact_table WHERE id = ?"
    cursor.execute(query, (id,))
    conn.commit()

def delete_my_contact_multiple(ids):
    query = "DELETE from contact_table WHERE id = ?"
    cursor.executemany(query, ids)
    conn.commit()


init_connections()
delete_my_contact_single(17)
delete_my_contact_multiple([(15,),(16,)])

close_connecton()

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. OK Read More