如何使用 Python 在 MySQL 中使用 IF 语句?

IF 语句是 Python 中的条件语句。它检查特定条件并相应地执行某些操作。

在这里,我们将讨论使用 IF 语句使用 python 与 sql 数据库进行交互。

语法

IF(condition, value_if_true,value_if_false)

IF 语句可以与 SELECT 子句一起使用,以根据某些条件执行选择。

在python中使用IF语句从使用MySQL的表中选择数据的步骤

  • 导入 MySQL 连接器

  • 使用连接器建立连接 connect()

  • 使用cursor()方法创建游标对象

  • 使用适当的 mysql 语句创建查询

  • 使用execute()方法执行 SQL 查询

  • 关闭连接

假设我们有以下名为“MyTable”的表

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

示例

我们将使用带有上表的 IF 语句如下

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()
输出结果
(200, ‘FAIL’ )
(500, ‘FAIL’ )
(1000, ‘PASS’)
(600, ‘PASS’)
(100, ‘FAIL’)
(150, ‘FAIL’ )
(700, ‘PASS’)

上面的代码将值 FAIL 分配给小于 500 的值,将 PASS 分配给大于 500 的值。