python操作sqlite数据库

用db browser建一个student数据库 在建一个学生分数表

 

 

 Python查询数据

import sqlite3

# 定义数据库文件名
db_file = "student.db"
# 连接数据库
conn = sqlite3.connect(db_file)

# 定义sql语句并执行
sql = "select * from fens"
cur = conn.cursor()
cur.execute(sql)

# 打印结果
print(cur.fetchall())
# 关闭连接
conn.close()

 

打印结果:

 

 

 python添加数据

import sqlite3

# 定义数据库文件名
db_file = "student.db"
# 连接数据库
conn = sqlite3.connect(db_file)

# 插入数据库
sql = "insert into fens (name,math,chinese) values ('王五',100,99)"
cur = conn.cursor()
cur.execute(sql)
conn.commit() # 一定要提交数据

# 关闭连接
cur.close()
conn.close()

 

 python删除数据

import sqlite3

# 定义数据库文件名
db_file = "student.db"
# 连接数据库
conn = sqlite3.connect(db_file)

# 插入数据库
sql = "delete from fens where id=5"
cur = conn.cursor()
cur.execute(sql)
conn.commit() # 一定要提交数据

# 关闭连接
cur.close()
conn.close()

 

 python修改数据

import sqlite3

# 定义数据库文件名
db_file = "student.db"
# 连接数据库
conn = sqlite3.connect(db_file)

# 插入数据库
sql = "update fens set chinese=50 where name='张三'"
cur = conn.cursor()
cur.execute(sql)
conn.commit() # 一定要提交数据

# 关闭连接
cur.close()
conn.close()

 

简单封装

import sqlite3
from sqlite3 import Error

# 获取连接
def get_db_conn(db_file):
    conn = None
    try:
        conn = sqlite3.connect(db_file)
    except Error as e:
        print(e)
    if conn is not None:
        return conn
    
# 关闭资源
def close_db_conn(cur,conn):
    if cur is not None:
        cur.close()
    if conn is not None:
        conn.close()

 

posted @ 2022-04-18 15:00  波罗斯の程序日记  阅读(278)  评论(0编辑  收藏  举报