Python使用sqlite3第三方庫讀寫SQLite數(shù)據(jù)庫的方法步驟
1 數(shù)據(jù)概覽
學(xué)生課程成績:studentID、name、english、chinese、math,存在一定缺失值

2 任務(wù)定義
基于學(xué)生課程成績文件,使用pandas和sqlite3將學(xué)生信息輸入SQLite數(shù)據(jù)庫,請在完成對應(yīng)數(shù)據(jù)庫操作后分析學(xué)生課程成績信息,計算各科目平均分并給出總分排名。
3 實現(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ù)庫和學(xué)生表
# 創(chuàng)建學(xué)生成績數(shù)據(jù)庫
conn=sqlite3.connect("./Database/Student_grade.db")
## 創(chuàng)建游標(biāo)
cursor=conn.cursor()
## 創(chuàng)建成績表
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ù)庫
# 將學(xué)生信息存入數(shù)據(jù)庫
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'],
)
# 執(zhí)行語句
cursor.execute(insert_sql)
# 事物提交
conn.commit()

3.4 將李四數(shù)學(xué)成績70錄入SQLite數(shù)據(jù)庫
# 錄入李四的數(shù)學(xué)成績
grade_LiSi=70
# 更新語句
update_sql='UPDATE student_grades SET scoreMath={} WHERE studentID=10002'.format(grade_LiSi)
# 執(zhí)行語句
cursor.execute(update_sql)
# 事物提交
conn.commit()
# 查詢錄入李四成績后的信息
select_sql='SELECT * FROM student_grades;'
# 執(zhí)行語句
results=cursor.execute(select_sql)
# 遍歷輸出
for info in results.fetchall():
print(info)

3.5 將數(shù)據(jù)庫中的王五數(shù)學(xué)成績改為85
# 更新王五的數(shù)學(xué)成績
grade_WangWu=85
# 更新語句
update_sql='UPDATE student_grades SET scoreMath={} WHERE studentID=10003'.format(grade_WangWu)
# 執(zhí)行語句
cursor.execute(update_sql)
# 事物提交
conn.commit()
# 查詢王五的成績
select_sql='SELECT * FROM student_grades WHERE studentID=10003;'
# 執(zhí)行語句
results=cursor.execute(select_sql)
# 遍歷輸出
for info in results.fetchall():
print(info)

3.5 計算學(xué)生的各科平均分,并給出總分排名
# 查詢數(shù)據(jù)
select_sql='SELECT * FROM student_grades;'
# 執(zhí)行語句
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:])
# 計算平均分的函數(shù)
def average_score(lst):
return round(sum(lst)/len(lst),2)
# 輸出結(jié)果
print("英語平均分為:", average_score(english_lst))
print("語文平均分為:", average_score(chinese_lst))
print("數(shù)學(xué)平均分為:", average_score(math_lst))
print("總成績排名為:", sorted(total_dct.items(), key=lambda x:x[1], reverse=True))

4 小小的總結(jié)
在Python中使用sqlite3:
連接數(shù)據(jù)庫:conn=sqlite3.connect(filename),如果數(shù)據(jù)庫不存在,會自動創(chuàng)建再連接。創(chuàng)建游標(biāo):cursor=conn.cursor(),SQL的游標(biāo)是一種臨時的數(shù)據(jù)庫對象,即可以用來
存放在數(shù)據(jù)庫表中的數(shù)據(jù)行副本,也可以指向存儲在數(shù)據(jù)庫中的數(shù)據(jù)行的指針。游標(biāo)提供了在逐行的基礎(chǔ)上操作表中數(shù)據(jù)的方法。
運用sqlite3運行SQL語句的框架:
① 定義sql語句,存儲到字符串sql中
② 使用游標(biāo)提交執(zhí)行語句:cursor.execute(sql)
③ 使用連接提交事務(wù):conn.commit()
到此這篇關(guān)于Python使用sqlite3第三方庫讀寫SQLite數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)Python讀寫SQLite數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python中如何使用sqlite3操作SQLite數(shù)據(jù)庫詳解
- 使用Python連接SQLite數(shù)據(jù)庫的操作步驟
- 通過python封裝SQLite3的示例代碼
- Python數(shù)據(jù)庫編程之SQLite和MySQL的實踐指南
- Python的sqlite3模塊中常用函數(shù)
- Python中SQLite數(shù)據(jù)庫的使用
- Python數(shù)據(jù)庫sqlite3圖文實例詳解
- Python練習(xí)之操作SQLite數(shù)據(jù)庫
- python處理SQLite數(shù)據(jù)庫的方法
- SQLite5-使用Python來讀寫數(shù)據(jù)庫
- Pandas使用SQLite3實戰(zhàn)
相關(guān)文章
Python編譯成.so文件進(jìn)行加密后調(diào)用的實現(xiàn)
今天小編就為大家分享一篇Python編譯成.so文件進(jìn)行加密后調(diào)用的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python socket套接字實現(xiàn)C/S模式遠(yuǎn)程命令執(zhí)行功能案例
這篇文章主要介紹了Python socket套接字實現(xiàn)C/S模式遠(yuǎn)程命令執(zhí)行功能,涉及Python socket套接字編寫服務(wù)器/客戶機(jī)模式數(shù)據(jù)傳輸相關(guān)操作技巧,需要的朋友可以參考下2018-07-07
Python數(shù)據(jù)分析?Pandas?Series對象操作
這篇文章主要介紹了Python數(shù)據(jù)分析之Pandas?Series對象,文章基于python的相關(guān)資料展開詳細(xì)內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-05-05

