脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python使用sqlite3第三方库读写SQLite数据库的方法步骤

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

2022-07-04 16:13fangyibo24 Python

数据库非常重要,程序的数据增删改查需要数据库支持,python处理数据库非常简单,而且不同类型的数据库处理逻辑方式大同小异,下面这篇文章主要给大家介绍了关于Python使用sqlite3第三方库读写SQLite数据库的方法步骤,需要的朋友可以

1 数据概览

学生课程成绩:studentID、name、english、chinese、math,存在一定缺失值

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

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")

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

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()

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

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)

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

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)

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

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))

Python使用sqlite3第三方库读写SQLite数据库的方法步骤

4 小小的总结

Python中使用sqlite3:

连接数据库:conn=sqlite3.connect(filename),如果数据库不存在,会自动创建再连接。创建游标:cursor=conn.cursor(),SQL的游标是一种临时的数据库对象,即可以用来

存放在数据库表中的数据行副本,也可以指向存储在数据库中的数据行的指针。游标提供了在逐行的基础上操作表中数据的方法。

运用sqlite3运行SQL语句的框架:

① 定义sql语句,存储到字符串sql中

② 使用游标提交执行语句:cursor.execute(sql)

③ 使用连接提交事务:conn.commit()

到此这篇关于Python使用sqlite3第三方库读写SQLite数据库的文章就介绍到这了,更多相关Python读写SQLite数据库内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文地址:https://blog.csdn.net/fangyibo24/article/details/123476900

延伸 · 阅读

精彩推荐