Python MariaDB – Update Query using PyMySQL

MariaDB is an open-source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python.

In this article, we will look into the process of using the UPDATE query on a table of the database using pymysql.  The update is used to change the existing values in a database. By using the update statement a specific value can be corrected or updated. It only affects the data and not the structure of the table. The basic advantage provided by this command is that it keeps the table accurate.

Syntax :

UPDATE tablename
SET column_nmae = "new value"
WHERE conditions;

The following programs will help you understand this better.

Example 1 : 



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

import pymysql
  
# Create a connection object
# IP address of the MySQL database server
Host = "localhost"  
  
# User name of the database server
User = "user"       
  
# Password for the database user
Password = ""           
  
database = "GFG"
  
conn  = pymysql.connect(host=Host, user=User, password=Password, database)
  
# Create a cursor object
cur  = conn.cursor()
  
  
query = f"UPDATE PRODUCT SET price = 1400 WHERE PRODUCT_TYPE = 'broadband'"
  
cur.execute(query)
  
#To commit the changes
conn.commit() 
conn.close()

chevron_right


Output :

Before:
After

In the above program,  We update Broad Band price from 1200 to 1400.

Example 2 :

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

import pymysql
  
# Create a connection object
conn  = pymysql.connect('localhost', 'user',
                        'password', 'database')
  
# Create a cursor object
cur  = conn.cursor()
  
  
query = f"update PRODUCT set PRODUCT_ID = 'A123' WHERE \
price = 14782 AND PRODUCT_TYPE = 'Voice'"
  
cur.execute(query)
  
# To commit the changes
conn.commit()       
conn.close()

chevron_right


Output :

Before
After

In the above program,  We update PRODUCT_ID  to A123 WHERE price = 14782 AND PRODUCT_TYPE = ‘Voice’.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.