Python में MySQL database के existing records को update करने के लिए update statement use किया जाता है। हालाँकि किसी particular type के records update करने के लिए mostly इसे MySQL Where Clause के साथ use करते हैं।

Python MySQL Update Example

पिछले topics में users table में कुछ नए records को insert और select किया था म अब उन्ही records को update करने की कोशिश करेंगे।

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()
# update email where id=1.
query = "UPDATE users SET email = %s WHERE id=%s"
set_value = ('changedEmail@gmail.com', 1)
db_cursor.execute(query, set_value)
mydb.commit()
print(db_cursor.rowcount, ' Record Updated.')
# now see updated recod.
query = "SELECT * FROM users WHERE id=%s"
set_value = (1, )
db_cursor.execute(query, set_value)
print(db_cursor.fetchone())
Output
C:\Users\Rahulkumar\Desktop\python>python mysql_update.py
1  Record Updated.
(1, 'Rahul', 'Kumar', 'changedEmail@gmail.com')

Note* Example में id field के bases पर record update किया है , और table में id field unique होता है। इसलिए सिर्फ 1 record ही update हुआ है। अगर where clause में कोई ऐसा field लेते हैं जिसमे duplicate data है तो multiple records update हो जायँगे। और अगर where clause use नहीं करते तो table में सभी records update हो जायँगे।

rowcount property अभी update किये गए records का number return करता है।

Note : query execute करने के बाद कभी भी commit() करना न भूले , नहीं table में records update नहीं होंगे।


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

query = "UPDATE users SET email = 'changedEmail@gmail.com' WHERE id=1"
db_cursor.execute(query)
mydb.commit()

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

Related Topics :

Rahul Kumar

Rahul Kumar

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

b2eprogrammers