如何使用 Python 测试 MySQL 表中是否存在某条记录?
pythonserver side programmingprogramming
我们有时可能需要检查表中是否存在某条特定记录。
这可以使用 EXISTS 语句来完成。如果以下子查询返回一个或多个记录,则 EXISTS 语句返回 true。
语法
SELECT * FROM table_name WHERE EXISTS(sub_query)
如果子查询返回一个或多个行,则 EXISTS 将返回 true。
使用 MySQL 在 python 中检查表中是否存在记录的步骤
导入 MySQL 连接器
使用 connect() 与连接器建立连接
使用 cursor() 方法创建游标对象
使用适当的 mysql 语句创建查询
使用 execute() 方法执行 SQL 查询
关闭连接
假设我们有以下名为"Sales"的表
+------------+---------+ | sale_price | tax | +------------+---------+ | 1000 | 200 | | 500 | 100 | | 50 | 50 | | 180 | 180 | +------------+---------+
示例
import mysql.connector db=mysql.connector.connect(host="your host", user="your username", password="your password",database="database_name") cursor=db.cursor() query="SELECT sale_price FROM Sales WHERE EXISTS(SELECT * FROM Sales WHERE tax>150)" cursor.execute(query) rows=cursor.fetchall() for row in rows: print(row) db.close()
上述代码中的子查询返回 TRUE,因为有记录的税额大于 150。因此 EXISTS 语句返回 true。如果没有记录的税额大于 150,则 EXISTS 将返回 false。
输出
1000 500 700