
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- How to use nested if statement in Python?
- How to use multiple conditions in one if statement in Python?
- Explain the use of SELECT DISTINCT statement in MySQL using Python?
- How to use MySQL CASE statement while using UPDATE Query?
- How to use NULL in MySQL SELECT statement?
- How to use if...else statement at the command line in Python?
- How can I use MySQL IF() function within SELECT statement?
- How to compare two variables in an if statement using Python?
- How to use continue statement in Python loop?
- How to use a select statement while updating in MySQL?
- How to use else statement with Loops in Python?
- How to use OR condition in a JavaScript IF statement?
- Can we use break statement in a Python if clause?
- Can we use continue statement in a Python if clause?
- Can we use pass statement in a Python if clause?
