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ù)的方法。
運(yùn)用sqlite3運(yùn)行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)文章
DataFrame 將某列數(shù)據(jù)轉(zhuǎn)為數(shù)組的方法
下面小編就為大家分享一篇DataFrame 將某列數(shù)據(jù)轉(zhuǎn)為數(shù)組的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04使用Pycharm創(chuàng)建一個Django項目的超詳細(xì)圖文教程
Django是比較經(jīng)典的Python web框架,最近剛好在項目中用到了Django,所以下面這篇文章主要給大家介紹了關(guān)于使用Pycharm創(chuàng)建一個Django項目的超詳細(xì)圖文教程,文中介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08Python數(shù)據(jù)類型之Tuple元組實例詳解
這篇文章主要介紹了Python數(shù)據(jù)類型之Tuple元組,結(jié)合實例形式分析了Python元組類型的概念、定義、讀取、連接、判斷等常見操作技巧與相關(guān)注意事項,需要的朋友可以參考下2019-05-05Python圖片轉(zhuǎn)gif方式(將靜態(tài)圖轉(zhuǎn)化為分塊加載的動態(tài)圖)
這篇文章主要介紹了Python圖片轉(zhuǎn)gif方式(將靜態(tài)圖轉(zhuǎn)化為分塊加載的動態(tài)圖),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11Python實現(xiàn)基于二叉樹存儲結(jié)構(gòu)的堆排序算法示例
這篇文章主要介紹了Python實現(xiàn)基于二叉樹存儲結(jié)構(gòu)的堆排序算法,結(jié)合實例形式分析了Python二叉樹的定義、遍歷及堆排序算法相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2017-12-12matlab中imadjust函數(shù)的作用及應(yīng)用舉例
這篇文章主要介紹了matlab中imadjust函數(shù)的作用及應(yīng)用舉例,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02Python高級編程之消息隊列(Queue)與進(jìn)程池(Pool)實例詳解
這篇文章主要介紹了Python高級編程之消息隊列(Queue)與進(jìn)程池(Pool),結(jié)合實例形式詳細(xì)分析了Python消息隊列與進(jìn)程池的相關(guān)原理、使用技巧與操作注意事項,需要的朋友可以參考下2019-11-11