Update query
import mysql.connector
from mysql.connector import errorcode
try:
# Connecting with MySql
con = mysql.connector.connect(user='root', password='mysql', host='127.0.0.1', database='company')
# Using cursor() method to create cursor object
cursor = con.cursor()
# SQL query to update a record.
sql_query = "UPDATE EMPLOYEE SET JOB_PROFILE = 'Sr. Programmer' WHERE EMP_ID = 'E20021'"
# Executing query
cursor.execute(sql_query)
con.commit()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Your user name or password is incorrect")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
con.close()
Example: update using parameterized query
import mysql.connector
from mysql.connector import errorcode
try:
# Connecting with MySql
con = mysql.connector.connect(user='root', password='mysql', host='127.0.0.1', database='company')
# Using cursor() method to create cursor object
cursor = con.cursor()
# SQL query to update a record.
sql_query = "UPDATE EMPLOYEE SET JOB_PROFILE = %s WHERE EMP_ID = %s"
val = ("Sr. Java Programmer", "E20021")
# Executing query
cursor.execute(sql_query,val)
con.commit()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Your user name or password is incorrect")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
con.close()
Conclusion
Well, in this topic, we have learnt to update MySQL table by using Python script. While updating record, make sure you use proper where clouse, absence of where clouse may update all records of the table.
In our next topic, we will learn to drop table inside this database. Till then keep learning and practice.