How to use IF statement in MySQL using Python?


IF statement is a conditional statement in python. It checks for a particular condition and performs some action accordingly.

Here, we will discuss the use of IF statement using python to interact with the sql database.

Syntax

IF(condition, value_if_true,value_if_false)

The IF statemen tcan be used with the SELECT clause to perform selection based on some criteria .

Steps to use IF statement to select data from a table using MySQL in python

  • import MySQL connector

  • establish connection with the connector using connect()

  • create the cursor object using cursor() method

  • create a query using the appropriate mysql statements

  • execute the SQL query using execute() method

  • close the connection

Suppose we the following table named “MyTable”

+----------+---------+
|    id    | value   |
+----------+---------+
|        1 |    200  |
|        2 |    500  |
|        3 |    1000 |
|        4 |    600  |
|        5 |    100  |
|        6 |    150  |
|        7 |    700  |
+----------+---------+

Example

We will use the IF statement with the above table as follows

import mysql.connector
db=mysql.connector.connect(host="your host",user="your username",password="your
password",database="database_name")

cursor=db.cursor()

query="SELECT value, IF(value>500, ‘PASS’ , ‘FAIL’ ) FROM MyTable"
cursor.execute(query)

for row in cursor:
   print(row)
db.close()

Output

(200, ‘FAIL’ )
(500, ‘FAIL’ )
(1000, ‘PASS’)
(600, ‘PASS’)
(100, ‘FAIL’)
(150, ‘FAIL’ )
(700, ‘PASS’)

The above code assigns value FAIL to the values which are less than 500 and PASS to the values which are more than 500.

Updated on: 10-Jun-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements