Python使用sqlite3第三方库读写SQLite数据库的方法步骤

作者:fangyibo24 时间:2024-01-23 06:31:39 

1 数据概览

学生课程成绩:studentID、name、english、chinese、math,存在一定缺失值

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

2 任务定义

基于学生课程成绩文件,使用pandas和sqlite3将学生信息输入SQLite数据库,请在完成对应数据库操作后分析学生课程成绩信息,计算各科目平均分并给出总分排名。

3 实现步骤

3.1 利用pandas读取学生信息

import pandas as pd
import sqlite3
# 利用pandas读取数据
student_df=pd.read_csv("./Dataset/student_grades.csv",encoding='utf-8-sig')

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

3.2 利用sqlite3创建数据库和学生表

# 创建学生成绩数据库
conn=sqlite3.connect("./Database/Student_grade.db")
## 创建游标
cursor=conn.cursor()
## 创建成绩表
try:
   # 判断表是否存在, 存在则先删除
   dropif_sql='Drop TABLE IF EXISTS student_grades;'
   create_sql='''
       CREATE TABLE student_grades
       (
           studentID varchar(64),
           studentName varchar(64),
           scoreEnglish float(64),
           scoreChinese float(64),
           scoreMath float(64)
       )
   '''
   cursor.execute(dropif_sql)
   cursor.execute(create_sql)
except:
   print("Create table failed!")

3.3 利用sqlite3将学生信息存入数据库

# 将学生信息存入数据库
for i in range(student_df.shape[0]):
   print(student_df.loc[i,:].to_list())
   # 插入语句
   insert_sql='''
       INSERT INTO student_grades(studentID, studentName, scoreEnglish, scoreChinese, scoreMath)
       Values('%s','%s','%f','%f','%f')'''%(
           str(student_df.loc[i,'StudentID']),
           str(student_df.loc[i,'name']),
           student_df.loc[i,'english'],
           student_df.loc[i,'chinese'],
           student_df.loc[i,'math'],
       )
   # 执行语句
   cursor.execute(insert_sql)
   # 事物提交
   conn.commit()

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

3.4 将李四数学成绩70录入SQLite数据库

# 录入李四的数学成绩
grade_LiSi=70
# 更新语句
update_sql='UPDATE student_grades SET scoreMath={} WHERE studentID=10002'.format(grade_LiSi)
# 执行语句
cursor.execute(update_sql)
# 事物提交
conn.commit()
# 查询录入李四成绩后的信息
select_sql='SELECT * FROM student_grades;'
# 执行语句
results=cursor.execute(select_sql)
# 遍历输出
for info in results.fetchall():
   print(info)

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

3.5 将数据库中的王五数学成绩改为85

# 更新王五的数学成绩
grade_WangWu=85
# 更新语句
update_sql='UPDATE student_grades SET scoreMath={} WHERE studentID=10003'.format(grade_WangWu)
# 执行语句
cursor.execute(update_sql)
# 事物提交
conn.commit()
# 查询王五的成绩
select_sql='SELECT * FROM student_grades WHERE studentID=10003;'
# 执行语句
results=cursor.execute(select_sql)
# 遍历输出
for info in results.fetchall():
   print(info)

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

3.5 计算学生的各科平均分,并给出总分排名

# 查询数据
select_sql='SELECT * FROM student_grades;'
# 执行语句
results=cursor.execute(select_sql)
# 计算各科平均分以及总分排名
english_lst=[]
chinese_lst=[]
math_lst=[]
total_dct={}
for info in results.fetchall():
   english_lst.append(info[2])
   chinese_lst.append(info[3])
   math_lst.append(info[4])
   total_dct[info[1]]=sum(info[2:])

# 计算平均分的函数
def average_score(lst):
   return round(sum(lst)/len(lst),2)

# 输出结果
print("英语平均分为:", average_score(english_lst))
print("语文平均分为:", average_score(chinese_lst))
print("数学平均分为:", average_score(math_lst))
print("总成绩排名为:", sorted(total_dct.items(), key=lambda x:x[1], reverse=True))

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

4 小小的总结

在Python中使用sqlite3:

连接数据库:conn=sqlite3.connect(filename),如果数据库不存在,会自动创建再连接。创建游标:cursor=conn.cursor(),SQL的游标是一种临时的数据库对象,即可以用来

存放在数据库表中的数据行副本,也可以指向存储在数据库中的数据行的指针。游标提供了在逐行的基础上操作表中数据的方法。

运用sqlite3运行SQL语句的框架:

① 定义sql语句,存储到字符串sql中

② 使用游标提交执行语句:cursor.execute(sql)

③ 使用连接提交事务:conn.commit()

来源:https://blog.csdn.net/fangyibo24/article/details/123476900

标签:python,读写,sqlite数据库
0
投稿

猜你喜欢

  • Golang应用执行Shell命令实战

    2024-05-22 10:29:20
  • js 目录列举函数

    2024-06-05 09:12:50
  • 对numpy Array [: ,] 的取值方法详解

    2023-02-05 17:33:23
  • 网络基础-数据包

    2022-11-24 21:48:10
  • Python爬虫进阶之Beautiful Soup库详解

    2022-09-13 04:38:50
  • 利用Python编写的实用运维脚本分享

    2022-07-15 21:32:46
  • Python OpenCV识别行人入口进出人数统计

    2023-09-18 13:08:06
  • PHP的mysqli_set_charset()函数讲解

    2023-07-11 06:22:17
  • matplotlib.pyplot.matshow 矩阵可视化实例

    2022-01-04 02:57:21
  • 隐藏你的.php文件的实现方法

    2023-10-20 22:58:01
  • centos7 PHP环境搭建 GD库 等插件安装方法

    2023-11-05 21:25:38
  • Linux下mysql新建账号及权限设置方法

    2024-01-22 21:38:07
  • Pyqt实现简易计算器功能

    2022-05-10 13:00:51
  • Pytorch1.5.1版本安装的方法步骤

    2021-02-07 00:57:09
  • python中Matplotlib绘制直线的实例代码

    2022-09-24 18:27:52
  • 关于jquery css的使用介绍

    2024-04-22 22:21:45
  • Python数据分析之Numpy库的使用详解

    2021-06-14 02:54:53
  • 触手生春【4.14】CSS与HTML结构

    2008-12-09 18:10:00
  • Python+Tableau广东省人口普查可视化的实现

    2022-02-12 21:53:59
  • 斜角滑动门导航条 DIV+CSS

    2008-07-19 15:45:00
  • asp之家 网络编程 m.aspxhome.com