👉 项目官网:https://www.python-office.com/ 👈
大家好,这里是程序员晚枫,正在all in AI编程实战 。
今天教你怎么用 Python 操作 SQLite 数据库 ——不需要安装任何软件,一个文件就是一个数据库!
1、什么是SQLite? SQLite 是一个轻量级数据库,所有数据存在一个文件里:
不需要安装数据库服务器 不需要配置 一个 .db 文件就是整个数据库 适合小中型项目数据存储 2、创建数据库和表 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import sqlite3conn = sqlite3.connect('test.db' ) cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, score REAL ) ''' )conn.commit() conn.close() print ('数据库和表创建完成!' )
3、插入数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import sqlite3conn = sqlite3.connect('test.db' ) cursor = conn.cursor() cursor.execute(''' INSERT INTO students (name, age, score) VALUES ('张三', 18, 95.5) ''' )students = [ ('李四' , 19 , 88.0 ), ('王五' , 20 , 92.5 ), ('赵六' , 18 , 85.0 ) ] cursor.executemany('INSERT INTO students (name, age, score) VALUES (?, ?, ?)' , students) conn.commit() conn.close() print ('数据插入完成!' )
4、查询数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import sqlite3conn = sqlite3.connect('test.db' ) cursor = conn.cursor() cursor.execute('SELECT * FROM students' ) rows = cursor.fetchall() for row in rows: print (f'ID: {row[0 ]} , 姓名: {row[1 ]} , 年龄: {row[2 ]} , 分数: {row[3 ]} ' ) cursor.execute('SELECT * FROM students WHERE score > 90' ) high_scorers = cursor.fetchall() print (f'90分以上: {high_scorers} ' )conn.close()
5、更新数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import sqlite3conn = sqlite3.connect('test.db' ) cursor = conn.cursor() cursor.execute(''' UPDATE students SET score = score + 5 WHERE score < 90 ''' )print (f'更新了 {cursor.rowcount} 条记录' )conn.commit() conn.close()
6、删除数据 1 2 3 4 5 6 7 8 9 10 11 12 import sqlite3conn = sqlite3.connect('test.db' ) cursor = conn.cursor() cursor.execute('DELETE FROM students WHERE name = "张三"' ) print (f'删除了 {cursor.rowcount} 条记录' )conn.commit() conn.close()
7、实战案例:员工信息管理系统 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 import sqlite3import officeclass EmployeeManager : def __init__ (self, db_path ): self.conn = sqlite3.connect(db_path) self.cursor = self.conn.cursor() self.create_table() def create_table (self ): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS employees ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, department TEXT, position TEXT, salary REAL ) ''' ) self.conn.commit() def add (self, name, department, position, salary ): self.cursor.execute(''' INSERT INTO employees (name, department, position, salary) VALUES (?, ?, ?, ?) ''' , (name, department, position, salary)) self.conn.commit() print (f'员工 {name} 已添加' ) def list_all (self ): self.cursor.execute('SELECT * FROM employees' ) return self.cursor.fetchall() def search (self, keyword ): self.cursor.execute(''' SELECT * FROM employees WHERE name LIKE ? OR department LIKE ? ''' , (f'%{keyword} %' , f'%{keyword} %' )) return self.cursor.fetchall() def export_to_excel (self, filename ): data = self.list_all() if data: data.insert(0 , ['ID' , '姓名' , '部门' , '职位' , '工资' ]) office.excel.write(path=filename, data=data) print (f'已导出到 {filename} ' ) manager = EmployeeManager('employees.db' ) manager.add('张三' , '技术部' , 'Python开发' , 15000 ) manager.add('李四' , '市场部' , '市场经理' , 12000 ) for emp in manager.list_all(): print (emp) manager.export_to_excel('员工表.xlsx' )
8、常见问题 Q:数据库文件在哪里?
A:在运行脚本的目录下,名为 test.db。
Q:数据会丢失吗?
A:每次修改后 commit() 才会保存到文件。
Q:可以同时多人操作吗?
A:SQLite 不适合高并发,多人同时写入可能出问题。
9、下讲预告 学会了数据库,下一讲我们学 JSON和CSV :处理结构化数据文件。
敬请期待!
有问题欢迎加微信 python-office 进群交流~
程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》 就能上手做AI项目。
🎓 AI 编程实战课程 想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!