什么是 fetchone() 方法?解释它在 MySQL Python 中的用途?

pythonserver side programmingprogramming更新于 2025/6/24 6:36:17

Fetchone() 方法

当您只想从表中选择第一行时,使用 Fetchone() 方法。此方法仅返回 MySQL 表中的第一行。

fetchone() 方法的使用

fetchone() 不用作要用于游标对象的查询。传递的查询是 “SELECT *”,它从表中提取所有行。稍后,我们对 “SELECT *” 返回的结果操作 fetchone() 方法。然后,fetchone() 方法从该结果中提取第一行。

使用 Python 中的 MySQL 从表中获取第一行需要遵循的步骤

  • 导入 MySQL 连接器

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

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

  • 使用“SELECT *”语句创建查询

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

  • 对“SELECT *”查询返回的结果操作 fetchone() 方法。

  • 关闭连接

假设我们有一个名为“MyTable”的表我们只想获取其中的第一行。

+----------+---------+-----------+------------+
|    Name  |  Class  |    City   |    Marks   |
+----------+---------+-----------+------------+
|    Karan |    4    | Amritsar  |    95      |
|    Sahil |    6    | Amritsar  |    93      |
|    Kriti |    3    | Batala    |    88      |
|   Khushi |    9    | Delhi     |    90      |
|    Kirat |    5    | Delhi     |    85      |
+----------+---------+-----------+------------+

示例

import mysql.connector

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

query="SELECT * FROM MyTable"
cursor.execute(query)

#the cursor object has all the rows returned by the query
#get the first row using the fetchone() method
first_row=cursor.fetchone()
print(first_row)

上述代码从表中获取第一行并打印它。

输出

(‘Karan’, 4, ‘Amritsar’ , 95)

相关文章


有用资源