Python SQLite – Update Specific Column
Last Updated :
28 Apr, 2021
In this article, we will discuss how to update a specific column of a table in SQLite using Python.
In order to update a particular column in a table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2…., column n = value n
WHERE [condition];
Below are some examples which depict how to use UPDATE query in SQLite using Python.
Example 1: We are going to create a STUDENT table and then perform update operations in it by updating the SNAME of a student whose SID is 1 in the table.
Python3
import sqlite3
connection = sqlite3.connect( 'gfg.db' )
connection.execute(
)
connection.execute(
"INSERT INTO STUDENTS VALUES (1, 'mohan pavan', 22, 'ponnur' )" )
connection.execute(
"INSERT INTO STUDENTS VALUES (2, 'sudheer', 28, 'chebrolu' )" )
connection.execute(
"INSERT INTO STUDENTS VALUES (3, 'mohan', 22, 'tenali' )" )
cursor = connection.execute( "SELECT * from STUDENTS" )
print ( '\nOriginal Table:' )
for row in cursor:
print (row)
connection.execute( "UPDATE STUDENTS set SNAME = 'sravan' where SID = 1" )
connection.commit()
cursor = connection.execute( "SELECT * from STUDENTS" )
print ( '\nUpdated Table:' )
for row in cursor:
print (row)
|
Output:
Example 2:
Here is another program where we update the ADDRESS of all the rows whose SAGE column value is 22 in the same table.
Python3
import sqlite3
connection = sqlite3.connect( 'gfg.db' )
connection.execute(
"INSERT INTO STUDENTS VALUES (5, 'mohan pavan', 22, 'ponnur' )" )
connection.execute(
"INSERT INTO STUDENTS VALUES (6, 'sudheer', 28, 'chebrolu' )" )
connection.execute(
"INSERT INTO STUDENTS VALUES (7, 'mohan', 22, 'tenali' )" )
cursor = connection.execute( "SELECT * from STUDENTS" )
print ( '\nOriginal Table:' )
for row in cursor:
print (row)
connection.execute( "UPDATE STUDENTS set ADDRESS = 'naga' where SAGE = 22" )
connection.commit()
cursor = connection.execute( "SELECT * from STUDENTS" )
print ( '\nUpdated Table:' )
for row in cursor:
print (row)
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...