SQL DELETE FROM statement का use करके Table से किसी particular या multiple records को एक साथ delete कर सकते हैं।

Python MySQL Delete Example

Copy Fullscreen Close Fullscreen
# import connector class from mysql module.
import mysql.connector as myconn
mydb = myconn.connect(
  host = 'localhost',
  user = 'root',
  password = '',
  database = 'python_db'
db_cursor = mydb.cursor()

# check record before delete.
query = "SELECT * FROM users"
print('Total records before delete :', len(list(db_cursor)))

# now delete a record , where last_name is 'Singh'.
query = "DELETE FROM users WHERE last_name=%s"
value = ('Singh', )
db_cursor.execute(query, value)
print(db_cursor.rowcount, ' Records deleted.')

# now check records.
query = "SELECT * FROM users"
print('Total records after delete :', len(list(db_cursor)))
C:\Users\Rahulkumar\Desktop\python>python mysql_delete.py
Total records before delete : 7
2  Records deleted.
Total records after delete : 5

Example से आप समझ सकते हैं कि किस तरह से MySQL Table से records delete करते हैं।

Note : table में किसी भी तरह के update / insert / delete करने के बाद commit() करना जरूरी होता है , नहीं तो table में records delete नहीं होंगे।

हालाँकि अगर आप चाहें तो , normally MySQL query में ही values को pass करते हैं वैसे भी records delete कर सकते हैं।
Foe Example -

query = "DELETE FROM users WHERE last_name='Singh'"

Note* जहाँ तक हो सके query में direct values रखकर records update न करें, इससे SQL Injection के chances बढ़ जाते हैं। इसलिए values को escape करके ही queries use करें।

Python MySQL Delete All Records

WHERE CLAUSE के साथ delete statement use करने पर सिर्फ वही records delete होंगे जो condition से match करेंगे , table से सभी records delete करने के लिए query without WHERE CLAUSE के साथ run करते हैं।
For Example -

#replace table_name with your Table name.
query = "DELETE FROM table_name"

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.

Get connected with me. :) LinkedIn Twitter Instagram Facebook