UPDATE changes existing data in a table.
Prerequisites
The customers table from Insert Into Table.
Update Rows
Example
import mysql.connector
mydb = mysql.connector.connect(
host='localhost',
user='root',
password='your_password',
database='itronix'
)
mycursor = mydb.cursor()
sql = 'UPDATE customers SET address = %s WHERE address = %s'
mycursor.execute(sql, ('Chandigarh', 'Delhi'))
mydb.commit()
print(mycursor.rowcount, 'record(s) affected')
Explanation: SET gives the new value, WHERE chooses which rows to change.
Update Several Columns
Example
mycursor.execute(
'UPDATE customers SET name = %s, address = %s WHERE id = %s',
('Asha Sharma', 'Ludhiana', 1)
)
mydb.commit()
Warning: UPDATE Without WHERE
Note:
UPDATE customers SET address = 'X' changes every row. Always include WHERE.Common Errors
| Problem | Cause and fix |
|---|---|
| rowcount is 0 | No row matched, or the new value equals the old one. |
ModuleNotFoundError: No module named 'mysql' |
Run pip install mysql-connector-python. |
Access denied for user 'root'@'localhost' |
Wrong user name or password. |
Can't connect to MySQL server on 'localhost' |
The MySQL server is not running. Start it from MySQL Workbench, XAMPP or your system services. |
Unknown database 'itronix' |
Create the database first (see Create Database). |
Practice Exercises
- Change the address of customer id 2.
Interview Questions
Q: What happens if you forget WHERE in UPDATE?
All rows are updated.
Summary
Use UPDATE table SET col = %s WHERE condition, then commit.
Machine Learning Tutorials, Courses and Certifications