Python MySQL Delete


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"
db_cursor.execute(query)
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)
mydb.commit()
print(db_cursor.rowcount, ' Records deleted.')

# now check records.
query = "SELECT * FROM users"
db_cursor.execute(query)
print('Total records after delete :', len(list(db_cursor)))
Output
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'"
db_cursor.execute(query)
mydb.commit()

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"
db_cursor.execute(query)
mydb.commit()

Hey ! I'm Rahul founder of learnhindituts.com. Working in IT industry more than 4.5 years. I love to talk about programming as well as writing technical tutorials and blogs that can help to others .... keep learning :)

Get connected with me - LinkedIn Twitter Instagram Facebook