什麼是 fetchone() 方法?解釋它在 MySQL Python 中的用途。
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)
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP