当前位置:首页 > 数据库 > SQlite

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

创建了此程序,以将列车编号和名称插入数据库.名称和数字是正确的(注释的打印语句证明了这一点),但是当我使用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()

但是,当我尝试读取此数据库时,它为空.

读取db的代码:

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)

我试图在sqlitebrowser中打开此数据库,只是为了确保它仍然是空的,因此我的第一个程序出现了问题,无法插入值.为什么这样?

解决方法:

你必须打电话

conn.commit()

之前

conn.close()

以便插入.这是Python/sqlite gotcha.


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!