本文共 3053 字,大约阅读时间需要 10 分钟。
import sqlite3#2、数据库文件db_file = 'score.db'#3、获取与数据库的连接conn = sqlite3.connect(db_file)#4、编写sql语句sql='select * from scores'#5、执行sql语句cur=conn.cursor()cur.execute(sql)#6、打印结果print(cur.fetchall())#7、关闭连接conn.close()
# SQlite数据库是一种嵌入式的数据库,它的数据库就是一个文件score.db# 经常被集成到各种应用程序中,并且在Sqlite中直接使用# 数据库:关系型数据库,一个数据库中有多张表,表和表之间通过主外键进行关连# python中操作sqlite数据库# 获取connection# 连接之后需要打开游标,cursor,通过cursor执行SQL语句# 关闭连接,释放资源import sqlite3db_file='score.db'#插入数据def insert_score_data(): #1.获取连接 conn=sqlite3.connect(db_file) #2.打开游标cursor cur=conn.cursor() #3.插入sql语句 #insert into +表名(列1,列2,列3...)values(?,?,?...) sql='insert into scores (stu_name,math_score,chinese_score) ' \ 'values(?,?,?)' #插入数据时需要使用元组类型 data=('赵五',89.9,78.2) cur.execute(sql,data) #执行插入时,需要进行显示提交数据,否则数据无法同步到数据库中 conn.commit() #4关闭资源 cur.close() conn.close()insert_score_data()
#插入多条语句score_list =[('jack',80,80,),('rose',85,85,),('liming',86,85,),('AMY',92,92,)]def insert_mult_data(): #1 获取连接 conn=sqlite3.connect(db_file) #2.打开游标 cur=conn.cursor() # sql语句 sql = 'insert into scores (stu_name,math_score,chinese_score) ' \ 'values(?,?,?)' #执行sql语句 插入多条数据 函数是executemany cur.executemany(sql,score_list) conn.commit() #3.关闭资源 cur.close() conn.close() return cur.rowcount# print(insert_mult_data())
#(删)删除数据:从数据库中删除记录,根据某种条件进行 wheredef delete_score_data(): #1.获取链接 conn=sqlite3.connect(db_file) #打开cursor游标,进行sql语句的执行 cur=conn.cursor() #删除的sql语句 delete from +表名 where 列=? sql='delete from scores where id=?' #构建元组数据 id=(2,) cur.execute(sql,id) #进行提交commit() conn.commit() #4.关闭资源 cur.close() conn.close()# delete_score_data()
#(改)修改数据,根据条件修改数据def updata_score_data(): #1 获取连接 conn=sqlite3.connect(db_file) #2 打开游标,执行sql语句 cur=conn.cursor() #修改的sql语句 update 表名 set 列名=?...where 条件 sql='update scores set math_score=?,chinese_score=? where id=3' # 元组数据的封装 data=(99,99,) cur.execute(sql,data) conn.commit() #关闭资源 cur.close() conn.close()# updata_score_data()
#(查)查询数据def select_score_all(): conn =sqlite3.connect(db_file) cur=conn.cursor() #构建查询语句 #查询 select 列名字 * 表示所有列 from 表名字 sql='select * from scores' cur.execute(sql) #打印数据 print(cur.fetchall()) #查询语句不需要commit, 不用同步到数据库 cur.close() conn.close()# select_score_all()
import sqlite3from 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()
#测试工具类,进行数据库的操作from db import get_db_conn,close_db_conndef get_data(): conn=get_db_conn(db_file) cur=conn.cursor() sql = 'select * from scores' cur.execute(sql) print(cur.fetchall()) close_db_conn(cur,conn)# get_data()
转载地址:http://xtgji.baihongyu.com/