我有一个简单的Python数据库应用程序与SQLite。我写了一个简单的程序来创建数据库并插入一些值。但是,数据库已创建,但未插入新值,但我不知道为什么:插入SQLite文件Python - 不起作用
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
import sys
def CreateTable():
try:
connection = lite.connect(':memory:')
with connection:
cursor = connection.cursor()
sql = 'CREATE TABLE IF NOT EXISTS Authors' + '(ID INT PRIMARY KEY NOT NULL, FIRSTNAME TEXT, LASTNAME TEXT, EMAIL TEXT)'
cursor.execute(sql)
data = '\n'.join(connection.iterdump())
with open('authors.sql', 'w') as f:
f.write(data)
except lite.Error, e:
if connection:
connection.rollback()
finally:
if connection:
cursor.close()
connection.close()
def Insert(firstname, lastname, email) :
try:
connection = lite.connect('authors.sql')
with connection:
cursor = connection.cursor()
sql = "INSERT INTO Authors VALUES (NULL, %s, %s, %s)" % (firstname, lastname, email)
cursor.execute(sql)
data = '\n'.join(connection.iterdump())
with open('authors.sql', 'w') as f:
f.write(data)
except lite.Error, e:
if connection:
connection.rollback()
finally:
if connection:
cursor.close()
connection.close()
CreateTable()
Insert('Tibby', 'Molko', '[email protected]')
为什么你有两个不同的数据库连接?一个是内存中,另一个是文件。 – 2015-04-06 11:24:17
,因为我需要在已创建的数据库中附加一些值。那可能吗? – yak 2015-04-06 11:24:46
然后只需打开一个连接到*那个数据库*。 SQLite数据库文件不像文本文件,你不会追加到它们。将它留给SQLite来管理文件中的数据。 – 2015-04-06 11:25:14