In some cases, we may want to update table data using update sql statement. Lets see how can we update.
The table which I am using to update record is as below.
emp_id | emp_name | emp_age |
---|---|---|
1 | Raj | 22 |
2 | Rahul | 24 |
3 | Vivek | 26 |
4 | Ajay | 28 |
5 | Suraj | 29 |
In the above table, lets say, I want to update the emp_name from Vivek to Birju whose id is 3.
If you have understanding of pymysql insert statement then following code is just a piece of cake for you. I have already discussed about insert statement. So check that tutorial.
Update Record
conn=pymysql.connect(‘localhost’,’root’,”,’emp_db’)
cursor=conn.cursor()
sql=”update emp_info set emp_name=’%s’ where id=%d ”
dataval=(‘Birju’,3)
try:
cursor.execute(sql)
conn.commit()
print(“data updated successfully”)
else pymysql.Error as pe:
print(pe)
conn.rollback()
finally:
cursor.close()
conn.close()
Output: data updated successfully
Note: Because we have changed the data in the table, so we must have to call conn.commit() function to make the changes permanent in the table.