coderz.py

Keep Coding Keep Cheering!

Update Query-MySQL

JOIN Clause

The UPDATE operation on any database updates one or more existing records in the database. The UPDATE statement in MySQL can be used to update the values of existing records. To update specific rows, use the WHERE clause in conjunction with it.

Syntax:

Below we have the basic syntax of the UPDATE statement:

UPDATE table_name SET column_name = new_value WHERE condition

The syntax above is used to update any specific row in a MySQL table. And, in order to specify which specific row of data we want to update, we use the WHERE clause to provide the condition to be matched while searching for the correct row of data to update.

Example:

Program to update the age of student with roll 21.

# Python program to demonstrate
# update clause


import mysql.connector

# Connecting to the Database
mydb = mysql.connector.connect(
host ='localhost',
database ='School',
user ='root',
)

cs = mydb.cursor()

# drop clause
statement ="UPDATE STUDENT SET AGE = 17  WHERE ROLL =21"

cs.execute(statement)
mydb.commit()

# Disconnecting from the database
mydb.close()

To see if the data has been successfully updated, we can use the following code to retrieve the students table data:

# Python program to demonstrate
# update clause


import mysql.connector

# Connecting to the Database
mydb = mysql.connector.connect(
host ='localhost',
database ='School',
user ='root',
)

cursor = db.cursor()
## defining the Query
query = "SELECT * FROM students"
## getting records from the table
cursor.execute(query)
## fetching all records from the 'cursor' object
records = cursor.fetchall()
## Showing the data
for record in records:
    print(record)

In the SELECT query too, we can use the WHERE clause to retrieve only the data of the row with rollno 21 or any other condition.

Note: also read about Select data from Table-MySQL

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement