- Python & MySQL 教程
- Python & MySQL - 首頁
- Python & MySQL - 概述
- Python & MySQL - 環境設定
- Python & MySQL 示例
- Python & MySQL - 連線資料庫
- Python & MySQL - 建立資料庫
- Python & MySQL - 刪除資料庫
- Python & MySQL - 選擇資料庫
- Python & MySQL - 建立表
- Python & MySQL - 刪除表
- Python & MySQL - 插入記錄
- Python & MySQL - 選擇記錄
- Python & MySQL - 更新記錄
- Python & MySQL - 刪除記錄
- Python & MySQL - WHERE 子句
- Python & MySQL - LIKE 子句
- Python & MySQL - 資料排序
- Python & MySQL - 使用連線
- Python & MySQL - 執行事務
- Python & MySQL - 錯誤處理
- Python & MySQL 有用資源
- Python & MySQL - 快速指南
- Python & MySQL - 有用資源
- Python & MySQL - 討論
Python & MySQL - 選擇記錄示例
在任何資料庫上進行選擇/讀取操作意味著從資料庫中獲取一些有用的資訊。
一旦建立了資料庫連線,就可以對該資料庫進行查詢了。可以使用fetchone()方法獲取單個記錄,或者使用fetchall()方法從資料庫表中獲取多個值。
fetchone() − 它獲取查詢結果集的下一行。結果集是在使用遊標物件查詢表時返回的物件。
fetchall() − 它獲取結果集中的所有行。如果結果集中已經提取了一些行,那麼它將檢索結果集中剩餘的行。
rowcount − 這是一個只讀屬性,返回受execute()方法影響的行數。
語法
# execute SQL query using execute() method. cursor.execute(sql) result = cursor.fetchall() for record in result: print(record)
| 序號 | 引數及描述 |
|---|---|
| 1 | $sql 必需 - 從表中選擇記錄的SQL查詢。 |
示例
嘗試以下示例從表中選擇記錄:
複製並貼上以下示例作為mysql_example.ty:
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","root","root@123", "TUTORIALS")
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "Select * from tutorials_tbl"
# execute SQL query using execute() method.
cursor.execute(sql)
# fetch all records from cursor
result = cursor.fetchall()
# iterate result and print records
for record in result:
print(record)
# disconnect from server
db.close()
輸出
使用python執行mysql_example.py指令碼並驗證輸出。
(1, 'HTML 5', 'Robert', datetime.date(2010, 2, 10)) (2, 'Java', 'Julie', datetime.date(2020, 12, 10)) (3, 'JQuery', 'Julie', datetime.date(2020, 5, 10))
廣告