查询数据
56.5 查询数据
SELECT 列 FROM 表 WHERE 条件 ORDER BY 列 LIMIT 条数。
fetchone() 取一行(元组),fetchall() 取全部,fetchmany(n) 取 n 条。
LIKE 模糊匹配:% 表示任意多个字符,_ 表示一个字符。
条件查询与排序
import sqlite3
with sqlite3.connect('school.db') as conn:
cur = conn.cursor()
cur.execute(
'SELECT name, score FROM students WHERE score >= ? ORDER BY score DESC LIMIT ?',
(80, 5)
)
for name, score in cur.fetchall():
print(name, score)
LIKE 模糊查姓名
import sqlite3
keyword = '小' # 实际项目来自 input
with sqlite3.connect('school.db') as conn:
cur = conn.execute(
"SELECT name, score FROM students WHERE name LIKE ?",
(f'%{keyword}%',)
)
print(cur.fetchall())