PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Databases » Python MySQL Execute Parameterized Query using Prepared Statement

Python MySQL Execute Parameterized Query using Prepared Statement

Updated on: March 9, 2021 | 18 Comments

This article demonstrates how to use a Python Parameterized query or Prepared Statement to perform MySQL database operations.

We use Parameterized query to use Python variable in SQL query. For example: –

  • We often need to pass variables to SQL select query in where clause to check some conditions.
  • In the user signup form user enter his/her details. You can take those values in Python variables and insert them into a table.

Further Reading:

  • Solve Python MySQL Exercise
  • Read Python MySQL Tutorial (Complete Guide)

For this article, we are going to use the Employee table present in my MySQL server. See its column details.

Employee table
Employee table

Table of contents

  • What is the Parameterized Query
    • Use of Parameterized Query and Prepared Statement
  • How to use Parameterized Query in Python
    • Example to insert data into MySQL table using Parameterized Query
    • Understand Python MySQL parameterized Query program
    • Use Parameterized Query Update data of MySQL table
    • Use Parameterized query and Prepared Statement to Delete data from MySQL table
  • Working of a Parameterized Query
  • Next Steps

What is the Parameterized Query

A parameterized query is a query in which placeholders (%s) are used for parameters (column values) and the parameter values supplied at execution time.

Let’s see the example of a parameterized query:

sql_parameterized_query = """Update employee set Salary = %s where id = %s"""

As you can see, we are using a placeholder (%s) for the salary and id column. We need to supply values in placeholders (%s) before executing a query. Pass Python variables at the placeholder’s position when we execute a query.

We need to pass the following two arguments to a cursor.execute() function to run a parameterized query.

  • SQL query
  • A tuple of parameter values. In our case, we need to pass two Python variables, one for salary and one for id.
query = """Update employee set Salary = %s where id = %s"""
tuple1 = (8000, 5)
cursor.execute(query, tuple1)

Use of Parameterized Query and Prepared Statement

There are the main 4 reasons to use. There are main four reasons to use.

There are four main reasons to use.

  • Compile Once: Parameterized query compiled only once. When you use parameterized query, it gets precompiled and stored in a PreparedStatement object. Now, use this object to execute the same statement multiple times efficiently. Note: For a standard query, MySQL compiles the query each time before running it.
  • Improves Speed: If you execute SQL statements repeatedly with a precompiled query, it reduces the execution time.
  • Same Operation with Different Data: You can use it to execute the same query multiple times with different data. For example, you want to insert 200 rows in a table. In such cases, use parameterized query to repeatedly execute the same operation with a different set of values.
  • It prevents SQL injection attacks.

Note: We are using MySQL Connector Python to execute a Parameterized query.

How to use Parameterized Query in Python

Create a Prepared statement object using a connection.cursor(prepared=True).

It creates a specific cursor on which statements are prepared and return a MySQLCursorPrepared class instance.

import mysql.connector
connection = mysql.connector.connect(host='localhost',
                             database='python_db',
                             user='pynative',
                             password='pynative@#29')

# this will retun MySQLCursorPrepared object
cursor = connection.cursor(prepared=True)

Example to insert data into MySQL table using Parameterized Query

Sometimes you need to insert a Python variable as a column value in the insert query. For example, a user has filled an online form and clicked on submit. So you need to insert those values into a MySQL table.

First, you need to take user input into a variable and pass that variable to the INSERT query as a placeholder (%s). All values are dynamic, i.e., depending on user input.

Let’s see how to use the parameterized query to insert data into the MySQL database using Python.

import mysql.connector

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='python_db',
                                         user='root')

    cursor = connection.cursor(prepared=True)
    # Parameterized query
    sql_insert_query = """ INSERT INTO Employee
                       (id, Name, Joining_date, salary) VALUES (%s,%s,%s,%s)"""
    # tuple to insert at placeholder
    tuple1 = (1, "Json", "2019-03-23", 9000)
    tuple2 = (2, "Emma", "2019-05-19", 9500)

    cursor.execute(sql_insert_query, tuple1)
    cursor.execute(sql_insert_query, tuple2)
    connection.commit()
    print("Data inserted successfully into employee table using the prepared statement")

except mysql.connector.Error as error:
    print("parameterized query failed {}".format(error))
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")

Output

Data inserted successfully into employee table using the prepared statement
MySQL connection is closed

Refer to fetch rows from MySQL table in Python using parameterized Query.

Understand Python MySQL parameterized Query program

  • First, we established the connection with MySQL from Python.
  • Next, we created a prepared statement object.
  • Next, we created the parameterized SQL query. In this query, we are using four placeholders for four columns.
  • Next, we added the value of four columns in the tuple in sequential order.
  • Next, we passed SQL insert query and tuple to a cursor.execute() method, remember tuple contains user data in the sequential order of placeholders.
  • n the end, we are committing our changes to the database using the connection.commit().
  • We placed our all code in the try-except block to catch exceptions if any.

Note: You can also create a prepared statement by explicitly passing the MySQLCursorPrepared class as an argument while creating a cursor.  

connection.cursor(cursor_class=MySQLCursorPrepared)

Use Parameterized Query Update data of MySQL table

Let’s see how to update the MySQL table using Python. In this example, we are updating the salary of an employee using a parameterized query.

import mysql.connector

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='python_db',
                                         user='pynative',
                                         password='pynative@#29')

    cursor = connection.cursor(prepared=True)
    sql_update_query = """UPDATE Employee set Salary = %s where Id = %s"""

    data_tuple = (12000, 1)
    cursor.execute(sql_update_query, data_tuple)
    connection.commit()
    print("Employee table updated using the prepared statement")

except mysql.connector.Error as error:
    print("parameterized query failed {}".format(error))
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")

Output:

Employee table updated using the prepared statement
MySQL connection is closed

Use Parameterized query and Prepared Statement to Delete data from MySQL table

Now, let’s see how to use the prepared statement and the parameterized query to delete the MySQL table’s data from Python.

For example, when user deleting their data from the web portal. In such a scenario, we need to use those variables inside a parameterized query using a placeholder (%s).

import mysql.connector

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='python_db',
                                         user='pynative',
                                         password='pynative@#29')

    cursor = connection.cursor(prepared=True)
    sql_Delete_query = """Delete from employee where id = %s"""
    empId = 2

    cursor.execute(sql_Delete_query, (empId,))
    connection.commit()
    print("Record Deleted successfully using Parameterized query")

except mysql.connector.Error as error:
    print("parameterized query failed {}".format(error))
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")

Output:

Record Deleted successfully using Parameterized query
MySQL connection is closed

Working of a Parameterized Query

The first time you pass a SQL query statement to the cursor’s execute() method, it creates the prepared statement.

For subsequent invocations of executing, the preparation phase is skipped if the SQL statement is the same, i.e., the query is not recompiled.

  • In the first cursor.execute(query, tuple) Python prepares statement i.e. Query gets compiled.
  • For subsequent execution calls of cursor.execute(query, tuple), The query gets executed directly with passed parameter values.

Next Steps

To practice what you learned in this article, Please solve a Python Database Exercise project to Practice and master the Python Database operations.

Filed Under: Python, Python Databases

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python Databases

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python Databases
TweetF  sharein  shareP  Pin

  Python MySQL

  • Python MySQL Connection Guide
  • Python MySQL Insert
  • Python MySQL Select
  • Python MySQL Update
  • Python MySQL Delete
  • Call MySQL Stored Procedure
  • Python MySQL Parameterized Query
  • Python MySQL Transactions
  • Python MySQL Connection Pooling
  • Python MySQL BLOB
  • Python Database Exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com