網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
Python使用sqlite3第三方庫(kù)讀寫SQLite數(shù)據(jù)庫(kù)的方法步驟_python
作者:fangyibo24 ? 更新時(shí)間: 2022-08-26 編程語(yǔ)言1 數(shù)據(jù)概覽
學(xué)生課程成績(jī):studentID、name、english、chinese、math,存在一定缺失值
2 任務(wù)定義
基于學(xué)生課程成績(jī)文件,使用pandas和sqlite3將學(xué)生信息輸入SQLite數(shù)據(jù)庫(kù),請(qǐng)?jiān)谕瓿蓪?duì)應(yīng)數(shù)據(jù)庫(kù)操作后分析學(xué)生課程成績(jī)信息,計(jì)算各科目平均分并給出總分排名。
3 實(shí)現(xiàn)步驟
3.1 利用pandas讀取學(xué)生信息
import pandas as pd
import sqlite3
# 利用pandas讀取數(shù)據(jù)
student_df=pd.read_csv("./Dataset/student_grades.csv",encoding='utf-8-sig')
3.2 利用sqlite3創(chuàng)建數(shù)據(jù)庫(kù)和學(xué)生表
# 創(chuàng)建學(xué)生成績(jī)數(shù)據(jù)庫(kù)
conn=sqlite3.connect("./Database/Student_grade.db")
## 創(chuàng)建游標(biāo)
cursor=conn.cursor()
## 創(chuàng)建成績(jī)表
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將學(xué)生信息存入數(shù)據(jù)庫(kù)
# 將學(xué)生信息存入數(shù)據(jù)庫(kù)
for i in range(student_df.shape[0]):
print(student_df.loc[i,:].to_list())
# 插入語(yǔ)句
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'],
)
# 執(zhí)行語(yǔ)句
cursor.execute(insert_sql)
# 事物提交
conn.commit()
3.4 將李四數(shù)學(xué)成績(jī)70錄入SQLite數(shù)據(jù)庫(kù)
# 錄入李四的數(shù)學(xué)成績(jī)
grade_LiSi=70
# 更新語(yǔ)句
update_sql='UPDATE student_grades SET scoreMath={} WHERE studentID=10002'.format(grade_LiSi)
# 執(zhí)行語(yǔ)句
cursor.execute(update_sql)
# 事物提交
conn.commit()
# 查詢錄入李四成績(jī)后的信息
select_sql='SELECT * FROM student_grades;'
# 執(zhí)行語(yǔ)句
results=cursor.execute(select_sql)
# 遍歷輸出
for info in results.fetchall():
print(info)
3.5 將數(shù)據(jù)庫(kù)中的王五數(shù)學(xué)成績(jī)改為85
# 更新王五的數(shù)學(xué)成績(jī)
grade_WangWu=85
# 更新語(yǔ)句
update_sql='UPDATE student_grades SET scoreMath={} WHERE studentID=10003'.format(grade_WangWu)
# 執(zhí)行語(yǔ)句
cursor.execute(update_sql)
# 事物提交
conn.commit()
# 查詢王五的成績(jī)
select_sql='SELECT * FROM student_grades WHERE studentID=10003;'
# 執(zhí)行語(yǔ)句
results=cursor.execute(select_sql)
# 遍歷輸出
for info in results.fetchall():
print(info)
3.5 計(jì)算學(xué)生的各科平均分,并給出總分排名
# 查詢數(shù)據(jù)
select_sql='SELECT * FROM student_grades;'
# 執(zhí)行語(yǔ)句
results=cursor.execute(select_sql)
# 計(jì)算各科平均分以及總分排名
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:])
# 計(jì)算平均分的函數(shù)
def average_score(lst):
return round(sum(lst)/len(lst),2)
# 輸出結(jié)果
print("英語(yǔ)平均分為:", average_score(english_lst))
print("語(yǔ)文平均分為:", average_score(chinese_lst))
print("數(shù)學(xué)平均分為:", average_score(math_lst))
print("總成績(jī)排名為:", sorted(total_dct.items(), key=lambda x:x[1], reverse=True))
4 小小的總結(jié)
在Python中使用sqlite3:
連接數(shù)據(jù)庫(kù):conn=sqlite3.connect(filename),如果數(shù)據(jù)庫(kù)不存在,會(huì)自動(dòng)創(chuàng)建再連接。創(chuàng)建游標(biāo):cursor=conn.cursor(),SQL的游標(biāo)是一種臨時(shí)的數(shù)據(jù)庫(kù)對(duì)象,即可以用來(lái)
存放在數(shù)據(jù)庫(kù)表中的數(shù)據(jù)行副本,也可以指向存儲(chǔ)在數(shù)據(jù)庫(kù)中的數(shù)據(jù)行的指針。游標(biāo)提供了在逐行的基礎(chǔ)上操作表中數(shù)據(jù)的方法。
運(yùn)用sqlite3運(yùn)行SQL語(yǔ)句的框架:
① 定義sql語(yǔ)句,存儲(chǔ)到字符串sql中
② 使用游標(biāo)提交執(zhí)行語(yǔ)句:cursor.execute(sql)
③ 使用連接提交事務(wù):conn.commit()
原文鏈接:https://blog.csdn.net/fangyibo24/article/details/123476900
相關(guān)推薦
- 2022-12-29 React中事件的類型定義方式_React
- 2022-09-10 ELK收集Tomcat日志的實(shí)現(xiàn)_Tomcat
- 2022-05-12 Android uniapp項(xiàng)目接入實(shí)例、uniapp混合開發(fā)踩坑手冊(cè)、uniapp Android
- 2023-05-29 Python常見異常的處理方式淺析_python
- 2022-07-08 從生成CRD到編寫自定義控制器教程示例_Golang
- 2022-09-01 C語(yǔ)言全面梳理結(jié)構(gòu)體知識(shí)點(diǎn)_C 語(yǔ)言
- 2022-12-08 用C語(yǔ)言求解一元二次方程的簡(jiǎn)單實(shí)現(xiàn)_C 語(yǔ)言
- 2022-04-11 android原生與kotlin驗(yàn)證碼倒計(jì)時(shí)
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支