Python MySQL UPDATE Query: Step-by-Step Guide in Python

0
317

Python MySQL UPDATE Query: Step-by-Step Guide in Python

This article is about the Python MySQL UPDATE Query to modify the records in your database. If you have a background in SQL, this tutorial will improve your knowledge in handling your database in Python.

Prerequisite

First things first – You need to set up your project. If in case you do not know how to do it, click the link to go to our step by step guide. Also, if you have any trouble in using the PIP command, just click the link to go to our easy step by step fix. Make sure you have a database to work on.

How to use Python MySQL UPDATE query

  1. Import mysql.connector

    This will connect your project/program to Python’s MySQL module so that your work can communicate to your database.

  2. Use the connect() method

    Using mysql.connector.connect() will establish a connection to your database. You can set the host, user, password, and database name as parameters of this method.

  3. Preparing the SQL

    Next is to prepare your query to update the records from your table. It is important here to know the fields in your table. Create an appropriately named variable to store your SQL. We will use this later as a parameter.

  4. The cursor() method

    This will create a cursor object that will interact with the database.

  5. Execute the UPDATE query with execute()

    Use your SQL variable as parameter for the execute method.

  6. Closing the connection

    Lastly, close the connection of your database.

Sample Code

Let us take a look at the example code. Just like the previous articles, the database used here is “python_db” with a “students” table.

The Output

You will get an output similar to this.

Parameterized Variation

Here is a parameterized version of the update query. Here, we created a function that needs the ID and the last name of the record. The ID will locate the record while the last name will be the new data. In the query, we substitute these values with placeholders “%s”.

Updating Multiple Records

Like the the INSERT query, you can update multiple records using the cursor.executemany() method.

Conclusion

That’s how you use Python MySQL UPDATE query in your projects. You can always expand and try different ways in implementing the UPDATE statement in your Python projects. Check out the different Python-related projects below:

Inquiries

If you have any questions or suggestions about the python mysql update query, please feel free to leave a comment below.

Looking for more source code? Type your keyword here here!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.