- 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 - 排序資料示例
Python 使用 c.execute(q) 函式,以從表格中使用排序語句選擇記錄(根據排序語句),其中 c 是游標,q 是將要執行的選擇查詢。
語法
# 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 order by tutorial_title asc"
# 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))
廣告