欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python使用sqlite3第三方庫讀寫SQLite數(shù)據(jù)庫的方法步驟

 更新時間:2022年07月04日 12:09:46   作者:fangyibo24  
數(shù)據(jù)庫非常重要,程序的數(shù)據(jù)增刪改查需要數(shù)據(jù)庫支持,python處理數(shù)據(jù)庫非常簡單,而且不同類型的數(shù)據(jù)庫處理邏輯方式大同小異,下面這篇文章主要給大家介紹了關(guān)于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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論