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

时间:2014-06-28 19:12:16

标签: python database sqlite

创建此程序以将列车编号和名称插入数据库。名称和数字是正确的(正如注释掉的print语句证明的那样)但是当我用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中打开这个数据库只是为了确保它仍然是空的,所以我的第一个程序无法插入值有问题。为什么这样?

1 个答案:

答案 0 :(得分:4)

你必须致电

conn.commit()

conn.close()

用于提交插入。这是Python/sqlite gotcha

相关问题