Python使用sqlite3第三方库读写SQLite数据库的方法步骤
作者:fangyibo24 发布时间:2024-01-23 06:31:39
标签:python,读写,sqlite数据库
1 数据概览
学生课程成绩:studentID、name、english、chinese、math,存在一定缺失值
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')
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()
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)
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)
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))
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


猜你喜欢
- 1.第一种就是直接调用 window.print()方法这种方法的坏处就是 默认打印整个页面,不能打印局部页面。2.第二种使用v-print
- python十进制转二进制python中十进制转二进制使用 bin() 函数。bin() 返回一个整数 int 或者长整数 long int
- 1. 加法运算示例代码:import torch# 这两个Tensor加减乘除会对b自动进行Broadcastinga = torch.ra
- 最近分别用vue和Android实现了一个券码复制功能,长按券码会在上方弹出一个拷贝的icon提示,点击icon将券码内容复制到剪贴板。现将
- 一、撤销修改(git add/rm 之前)git checkout -- * //是撤销从上次提交之后所做的所有修改git c
- 我就废话不多说了,大家还是直接看代码吧!def iou(y_true, y_pred, label: int): "&
- 适用的日志格式:106.45.185.214 - - [06/Aug/2014:07:38:59 +0800] "GET / HT
- 1.打开 database/migrations/2014_10_12_000000_create_users_table.php 这个 m
- 这里的内容以Linux进程基础和Linux文本流为基础。subprocess包主要功能是执行外部的命令和程序。比如说,我需要使用wget下载
- Mysql的存储过程是从版本5才开始支持的,所以目前一般使用的都可以用到存储过程。今天分享下自己对于Mysql存储过程的认识与了解。一些简单
- 当一台计算机上有多个网卡时,需要选择对应IP地址的网卡进行发送数据包或者接受数据包。1、选择网卡发包(应用scapy):plface=con
- 依赖包:pip install paramiko源码demo:from time import *import paramiko# 定义一个
- 本月第一天日期SELECT FirstDayOfCurrentMonth = dateadd(mm,datediff(mm,0,getdat
- 正则表达式正则表达用来匹配字符串正则表达式匹配过程依次拿出表达式和文本中的字符串进行比价如果每个字符都能匹配,则匹配成功;一旦有匹配不成功的
- 前置条件确保mysql的版本是5.7+一、新建mysql表增加json字段二、pojo类package com.cxstar.domain;
- 合并在numpy中合并两个arraynumpy中可以通过concatenate,参数axis=0表示在垂直方向上合并两个数组,等价于np.v
- 目录图像翻转图像轮廓排序图像轮廓排序颜色识别基础颜色识别根据BGR获取HSV阈值编辑器图像翻转使用Python的一个包,imutils。使用
- 本文实例讲述了Python使用内置json模块解析json格式数据的方法。分享给大家供大家参考,具体如下:Python中解析json字符串非
- 一、获取文件路径实现1.1 获取当前文件路径import oscurrent_file_path = __file__print(f&quo
- 彩色图像转换为灰度图像第一种方式通过 imread 读取图像的时候直接设置参数为 0 ,自动转换彩色图像为灰度图像第二种方式,可以通过 sp