Categories: python

Update Query-MySQL

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

Recent Posts

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

2 hours ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

3 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

3 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago