Skip to content
Related Articles

Related Articles

How to Use IF Statement in MySQL Using Python
  • Last Updated : 03 Jan, 2021

Prerequisite: Python: MySQL Create Table

In this article, we are going to see how to use if statements in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. 

Approach:

  • Import module.
  • Make a connection request with the database.
  • Create an object for the database cursor.
  • Execute the following MySQL query:
IF(condition, value_if_true, value_if_false)

Example 1:

In this example we are using this database table with the following query;



Below is the implementation:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Establish connection to MySQL database
import mysql.connector
  
db = mysql.connector.connect(
  host="localhost",
  user="root",
  password="root123",
  database = "geeks"
  )
  
#getting the cursor by cursor() method
mycursor = db.cursor()
  
insertQuery = " Select Value, IF(Value>1000,'MORE','LESS') from salary;"
mycursor.execute(insertQuery)
myresult = mycursor.fetchall()
print(myresult)
  
# close the Connection
db.close()

chevron_right


Output:

Example 2:

In this example we are using this database table with the following query;

Below is the full implementation:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Establish connection to MySQL database
import mysql.connector
  
db = mysql.connector.connect(
  host="localhost",
  user="root",
  password="root123",
  database = "geeks"
  )
  
#getting the cursor by cursor() method
mycursor = db.cursor()
  
insertQuery = " Select City, IF(City = 'Patna','True','False') from persons;"
mycursor.execute(insertQuery)
myresult = mycursor.fetchall()
  
print(myresult)
  
# close the Connection
db.close()

chevron_right


Output:


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
Recommended Articles
Page :