python操作sqlite3数据库,通过一般方法和使用pandas来读取显示数据库内容
本文通过两种方式来读取显示一个根目录下stu.db数据库中【student_scores】表的内容,【student_scores】表中有'级别', '班别', '学生姓名', '等级', '成绩'等关键字段。
#传统方法:
show_data(使用 params 参数传递两个查询参数,避免 SQL 注入)【显示】 调用 fetch_data()【查询】出来的【数据】,
【数据】通过connect_db(db_path)【连接】db_path指定的【数据库】获得。
#pandas方法:
show_data_pandas(使用 params 参数传递两个查询参数,避免 SQL 注入)【显示】 调用 fetch_data_pandas()【查询】出来的【数据】,
【数据】通过connect_db(db_path)【连接】db_path指定的【数据库】获得。
下面的示例是
show_data(2, 'D') # 一般方法查询班级为"2"班,成绩等级"D"并打印显示出来 show_data_pandas(1, 'C') # 通过pandas查询班级为"1"班,成绩等级"C"并打印显示出来
以下是示例的所有内容。
import os import sqlite3 import sys import logging import pandas as pd def connect_db(db_path): """连接数据库并返回连接对象""" try: conn = sqlite3.connect(db_path) return conn except sqlite3.Error as e: logging.error(f"连接数据库失败: {e}") sys.exit(1) def fetch_data(conn, class_id, grade): """从数据库中查询数据并返回结果""" try: cursor = conn.cursor() query = "SELECT * FROM student_scores WHERE 班别=? AND 等级=?" cursor.execute(query, (class_id, grade)) return cursor.fetchall() except sqlite3.Error as e: logging.error(f"查询数据失败: {e}") return [] def fetch_data_pandas(conn, class_id, grade): """使用 pandas 从数据库中查询数据""" try: # 使用参数化查询 query = "SELECT * FROM student_scores WHERE 班别=? AND 等级=?" data = pd.read_sql(query, conn, params=(class_id, grade)) # print(data) return data except sqlite3.Error as e: print(f"数据库连接失败: {e}") def show_data(class_id, grade): """显示数据""" db_path = 'stu.db' if not os.path.exists(db_path): logging.warning(f"数据库文件不存在,请检查{db_path}路径") return conn = connect_db(db_path) results = fetch_data(conn, class_id, grade) for row in results: print(row) conn.close() def show_data_pandas(class_id, grade): """显示pandas查询到的数据""" db_path = 'stu.db' if not os.path.exists(db_path): logging.warning(f"数据库文件不存在,请检查{db_path}路径") return conn = connect_db(db_path) results = fetch_data_pandas(conn, class_id, grade) print(results) conn.close() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) show_data(2, 'D') show_data_pandas(1, 'C')
如果要修改查询的关键字,可以更改这段最后的字段为你要查询的字段。
query = "SELECT * FROM student_scores WHERE 班别=? AND 等级=?"
注意:运行上面代码的前提是根目录有一个stu.db数据库,数据库里有个student_scores 表,表里有'级别', '班别', '学生姓名', '等级', '成绩'等字段,其中'班别'和'等级'必须有,因为前面sql查询语句里面指定了这两个条件。
微信扫一扫可微信查看访问。