查询与遍历

连上库后,查询要走游标 cursor。execute 发 SQL、fetchall 把结果一次性取回,每行是一个元组,for 循环就能逐行处理。

查询与遍历要点

查询与遍历示例

						import pymysql

						db = pymysql.connect(host="127.0.0.1", user="app_user", password="app_pass", database="shop_db")
						cursor = db.cursor()
						cursor.execute("SELECT order_id, amount, status FROM orders WHERE user_id = %s", (1,))
						rows = cursor.fetchall()
						for r in rows:
						    print(r)
						cursor.close()
						db.close()
避坑提醒:默认游标返回元组,列多时容易取错下标;想要按字段名取值,建游标时传 cursor=pymysql.cursors.DictCursor。
查询与遍历 · Python 连接 知识卡片
卡片 03 / 06 · Python 连接(1080×1440 速查卡片)

Python 连接知识点