一.Python 操作 SQLite
python
# Python 操作 SQLite
'''
工具 用途 优势
sqlite3 内置模块,操作 SQLite 数据库 无需安装,轻量,适合小项目
pymysql / mysql-connector-python 操作 MySQL 数据库 功能强大,社区活跃
psycopg2 操作 PostgreSQL 数据库 专业级数据库,性能好
SQLAlchemy ORM 框架(对象关系映射) 写代码更像操作 Python 对象,推荐用!
'''
import sqlite3
print(sqlite3.version)
# 1. 连接数据库(如果不存在,会自动创建)
conn = sqlite3.connect('students.db')
# 2. 创建游标对象(用于执行 SQL)
cursor = conn.cursor()
# 3. 创建表
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
grade REAL)
''')
# 4. 插入数据
cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
("张三", 18, 85.5))
cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
("李四", 17, 92.0))
# 5. 提交事务(非常重要!)
conn.commit()
# 6. 查询数据
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
print("所有学生信息:")
for row in rows:
print(row)
# 7. 关闭连接
conn.close()
二.SQLAlchemy 操作 SQLite
python
# SQLAlchemy 操作 SQLite
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 1. 创建数据库引擎(SQLite)
engine = create_engine('sqlite:///students_sqlalchemy.db', echo=True)
# 2. 创建基类
Base = declarative_base()
# 3. 定义学生模型(类)
class Student(Base):
__tablename__ = 'students'
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False)
age = Column(Integer)
grade = Column(Float)
# 4. 创建表
Base.metadata.create_all(engine)
# 5. 创建会话
Session = sessionmaker(bind=engine)
session = Session()
# 6. 插入数据(像操作 Python 对象一样)
student1 = Student(name="王五", age=16, grade=88.0)
student2 = Student(name="赵六", age=17, grade=91.5)
session.add(student1)
session.add(student2)
session.commit()
# 7. 查询数据
students = session.query(Student).all()
print("所有学生信息:")
for s in students:
print(f"ID: {s.id}, 姓名: {s.name}, 年龄: {s.age}, 成绩: {s.grade}")
# 8. 关闭会话
session.close()
三.本地运行sql 用 SQLite + Python
python
#本地运行sql 用 SQLite + Python
import sqlite3
# 连接数据库(如果文件不存在,会自动创建)
conn = sqlite3.connect('mydata.db')
# 创建游标(用于执行 SQL)
cursor = conn.cursor()
# 创建一个表格(比如学生信息表)
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
grade REAL)
''')
print(" 数据库和表已创建成功!")
# 保存更改
conn.commit()
# 关闭连接
conn.close()
四.示例学生信息管理系统
1.创建数据库和表格(学生信息管理系统)
python
# 1.创建数据库和表格(学生信息管理系统)
import sqlite3
# print(sqlite3.version)
def create_database():
# 连接数据库(如果不存在,自动创建)
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
# 创建学生表
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
grade REAL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
print(" 数据库和表 'students' 创建成功!")
conn.commit()
conn.close()
# 调用函数创建数据库
create_database()
2.插入数据(添加学生)
python
#2.插入数据(添加学生)
def insert_student(name, age, grade):
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
try:
cursor.execute('''
INSERT INTO students (name, age, grade)
VALUES (?, ?, ?)
''', (name, age, grade))
conn.commit()
print(f" 学生 '{name}' 添加成功!")
except Exception as e:
print(f" 添加失败:{e}")
finally:
conn.close()
# 示例:添加几个学生
insert_student("张三", 18, 85.5)
insert_student("李四", 17, 92.0)
insert_student("王五", 16, 88.0)
3.查看列表(查看学生列表)
python
#3.查看列表(查看学生列表)
def view_all_students():
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM students ORDER BY created_at DESC")
rows = cursor.fetchall()
if rows:
print("\n 所有学生信息:")
print("-" * 60)
for row in rows:
print(f"ID: {row[0]:2d} | 姓名: {row[1]:4s} | 年龄: {row[2]:2d} | 成绩: {row[3]:5.1f} | 添加时间: {row[4]}")
print("-" * 60)
else:
print(" 暂无学生数据。")
conn.close()
# 调用查看所有学生
view_all_students()
4.精确查找(按照名字查询)
python
#4.精确查找(按照名字查询)
def search_student_by_name(name):
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name = ?", (name,))
row = cursor.fetchone()
if row:
print(f" 找到学生:ID={row[0]}, 姓名={row[1]}, 年龄={row[2]}, 成绩={row[3]}")
else:
print(f" 未找到姓名为 '{name}' 的学生。")
conn.close()
# 示例:查找"张三"
search_student_by_name("张三")
view_all_students()
5.修改数据(更新成绩)
python
#5.修改数据(更新成绩)
def update_grade(name, new_grade):
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
cursor.execute("UPDATE students SET grade = ? WHERE name = ?", (new_grade, name))
if cursor.rowcount > 0:
print(f" 学生 '{name}' 的成绩已更新为 {new_grade}。")
else:
print(f" 未找到姓名为 '{name}' 的学生,更新失败。")
conn.commit()
conn.close()
# 示例:更新"李四"的成绩
update_grade("李四", 95.0)
view_all_students()
6.删除数据(按名字删除)
python
#6.删除数据(按名字删除)
def delete_student(name):
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
cursor.execute("DELETE FROM students WHERE name = ?", (name,))
if cursor.rowcount > 0:
print(f" 学生 '{name}' 已成功删除。")
else:
print(f" 未找到姓名为 '{name}' 的学生,删除失败。")
conn.commit()
conn.close()
# 示例:删除"王五"
delete_student("王五")
view_all_students()
7.从csv导入数据
python
#7.从csv导入数据
import csv
def import_from_csv(filename):
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
try:
with open(filename, 'r', encoding='utf-8') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
cursor.execute('''
INSERT INTO students (name, age, grade)
VALUES (?, ?, ?)
''', (row['name'], int(row['age']), float(row['grade'])))
conn.commit()
print(f" 成功从 '{filename}' 导入 {cursor.rowcount} 条数据!")
except Exception as e:
print(f" 导入失败:{e}")
finally:
conn.close()
# 调用导入函数
import_from_csv('students.csv')
整理不易,诚望各位看官点赞 收藏 评论 予以支持,这将成为我持续更新的动力源泉。若您在阅览时存有异议或建议,敬请留言指正批评,让我们携手共同学习,共同进取,吾辈自当相互勉励!