无法使用python将任何内容插入sqlite3数据库

sve*_*etu 3 python database sqlite

创建此程序以将列车编号和名称插入数据库。名称和数字是正确的(因为注释掉的打印语句证明了这一点)但是当我用 db reader 打开它时 db 文件是空的。

代码:

import sqlite3
import re

conn=sqlite3.connect('example.db')
c=conn.cursor()
c.execute('''CREATE TABLE train 
               (number text, name text)''')

f=open("train.htm","r")
html=f.read()

num=re.findall(r"(?<=> )[0-9]+", html) #regex to get train number
name=re.findall(r"(?<=<font>)[A-Za-z]+[ A-Za-z]+",html) #regex to get train name

j=8

for i in range(0,len(num)):
    #print(num[i],name[j]) #this statement proves that the values are right
    c.execute("INSERT INTO train VALUES (?,?)",(num[i],name[j]))
    j=j+3


conn.close()
Run Code Online (Sandbox Code Playgroud)

但是当我试图读取这个数据库时,它是空的。

读取数据库的代码:

import sqlite3

conn=sqlite3.connect('example.db')
c=conn.cursor()

for row in c.execute('SELECT * FROM train'):
    #the program doesn't even enter this block
    print(row)
Run Code Online (Sandbox Code Playgroud)

我尝试在 sqlitebrowser 中打开这个数据库只是为了确保它仍然是空的,所以我的第一个程序有问题,无法插入值。为什么这样?

unu*_*tbu 5

你必须打电话

conn.commit()
Run Code Online (Sandbox Code Playgroud)

conn.close()
Run Code Online (Sandbox Code Playgroud)

用于要提交的插入。这是一个Python/sqlite gotcha

  • 多次使用 `db.execute` 也是低效的,因为每次调用都在创建、使用、然后丢弃游标。 (2认同)