1、使用SQLite:Python内置
- 创建连接sqlite3.connect
- 创建游标conn.cursor
- 通过游标执行sql语句cursor.execute
('select * from user where id = ?', ('1',))
. ?为占位符 - 处理数据库返回结果cursor.rowcount,cursor.fetchall
- 关闭游标
- 提交事务:对表有修改(增删改)时需要提交
- 关闭连接
代码演示:打印出成绩在60-100之间的用户名
import os, sqlite3 db_file = 'db/school.db' if os.path.isfile(db_file): os.remove(db_file) # 初始数据: conn = sqlite3.connect(db_file) cursor = conn.cursor() cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)') cursor.execute(r"insert into user values ('A-001', 'Adam', 95)") cursor.execute(r"insert into user values ('A-002', 'Bart', 62)") cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)") def get_score_in(low, high): cursor.execute(r"select name from user where score>? and score<? order by score" , (low,high)) # 用 sql排序 # cursor.execute(r&# |