 
- 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 中创建一个表并插入两条记录。
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)