【问题标题】:Can't insert anything into sqlite3 Database using python无法使用python将任何内容插入sqlite3数据库
【发布时间】:2014-08-19 15:21:49
【问题描述】:

创建此程序以将列车号和名称插入数据库。名称和数字是正确的(正如注释掉的打印语句所证明的那样),但是当我用 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()

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

读取数据库的代码:

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 中打开这个数据库只是为了确保它仍然是空的,所以我的第一个程序有问题,无法插入值。为什么会这样?

【问题讨论】:

    标签: python database sqlite


    【解决方案1】:

    你必须打电话

    conn.commit()
    

    之前

    conn.close()
    

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

    【讨论】:

    • 有趣的链接。在该代码中,作者没有使用游标对象。打开数据库后可以去掉游标对象直接调用db函数吗?
    • 使用conn.execute 是 sqlite3 的“非标准”API 的一部分。我不建议使用它,因为如果您坚持使用DB-API 2.0 interface,您的代码将与其他数据库引擎更兼容。
    • 多次使用db.execute也效率低下,因为每次调用都是在创建、使用、然后丢弃光标。
    猜你喜欢
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2011-01-13
    • 1970-01-01
    • 2015-12-04
    • 2021-03-24
    相关资源
    最近更新 更多