If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
SQL DELETE FROM statement का use करके Table से किसी particular या multiple records को एक साथ delete कर सकते हैं।
# 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)))
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 करें।
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()
Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)
Get connected with me. :) LinkedIn Twitter Instagram Facebook