- 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 - 使用 Join
- Python 和 MySQL - 執行事務
- Python 和 MySQL - 處理錯誤
- Python 和 MySQL 有用資源
- Python 和 MySQL - 快速指南
- Python 和 MySQL - 有用資源
- Python 和 MySQL - 討論
Python 和 MySQL - 使用 Join 示例
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 表並插入兩條記錄。
create table tcount_tbl(
tutorial_author VARCHAR(40) NOT NULL,
tutorial_count int
);
insert into tcount_tbl values('Julie', 2);
insert into tcount_tbl values('Robert', 1);
示例
嘗試以下示例,使用 Join 從兩個表中獲取記錄。−
將以下示例複製並貼上為 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 a.tutorial_id, a.tutorial_author, b.tutorial_count
FROM tutorials_tbl a, tcount_tbl b
WHERE a.tutorial_author = b.tutorial_author"""
# 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, 'Robert', 1) (2, 'Julie', 2) (3, 'Julie', 2)
廣告