如何在Python中为SQLite数据库赋值并实现跨文件访问?
SQLite3数据插入后跨文件无法访问的解决方法
问题核心
在Python文件中向SQLite数据库插入数据后,当前文件能正常查询到数据,但切换到另一个文件访问时,表显示为空。
原因
SQLite默认开启事务机制,执行INSERT等写操作后,数据仅暂存于当前连接的内存中,若未显式提交事务,数据不会写入磁盘数据库,其他连接自然无法读取到这些数据。
解决方案
1. 显式提交事务
在插入数据后调用con.commit(),将内存中的数据持久化到磁盘:
修正后的添加数据文件代码:
import sqlite3 as sql con = sql.connect("db_Persons.db") cur = con.cursor() def setData(): cur.execute(""" INSERT INTO Persons (Name ,NumberPlate, Parking) VALUES( 'Alfred', 'DK12345', 0), ('Bent', 'DK45932', 0), ('Charlotte', 'DK84975',0), ('Dorte', 'DK98347', 0); """) setData() # 提交事务,将数据写入磁盘数据库 con.commit() # 查询并打印数据 Persons = cur.execute("""SELECT * from Persons""") records = Persons.fetchall() print("Total rows are: ", len(records)) print("Printing each row") for row in records: print("Id: ", row[0]) print("Name: ", row[1]) print("Licence Plate: ", row[2]) print("Parking Spot: ", row[3]) # 关闭连接 con.close()
2. 使用上下文管理器自动处理事务
推荐使用with语句创建连接,它会自动处理事务提交和连接关闭(无异常时自动提交,异常时自动回滚):
import sqlite3 as sql def setData(): with sql.connect("db_Persons.db") as con: cur = con.cursor() cur.execute(""" INSERT INTO Persons (Name ,NumberPlate, Parking) VALUES( 'Alfred', 'DK12345', 0), ('Bent', 'DK45932', 0), ('Charlotte', 'DK84975',0), ('Dorte', 'DK98347', 0); """) # 查询并打印数据 Persons = cur.execute("""SELECT * from Persons""") records = Persons.fetchall() print("Total rows are: ", len(records)) print("Printing each row") for row in records: print("Id: ", row[0]) print("Name: ", row[1]) print("Licence Plate: ", row[2]) print("Parking Spot: ", row[3]) setData()
内容的提问来源于stack exchange,提问作者GYMRAT369
相关产品推荐
相关产品推荐

