Sqlite3 Insertion不会保留Python的记录

时间:2016-09-23 01:15:34

标签: python python-2.7 sqlite

我正在尝试向sqlite数据库插入多个记录。这是我的测试脚本。

import sqlite3
from datetime import datetime
company = 'fghjk'
keyword = 'awesome'
filename = 'test.txt'
date_found = datetime.now()
conn = sqlite3.connect('C:\\sqlite\\test.db')
c = conn.cursor()

for i in range(0,4):
    insert_query = "INSERT into records (company,keyword,filename,date_found) values (?,?,?,?)"
    c.execute(insert_query, [company,keyword,filename,date_found])

select_query  = "SELECT * FROM records"
c.execute(select_query)
res = c.fetchall()
print res
for i in res:
    for b in i:
        print b

当我执行两次上面的脚本时,我希望有8条记录,但它总是返回4行。有人可以开导我吗?

输出:

1
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
2
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
3
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
4
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000

这是我的表的创建语句。

conn.execute('''CREATE TABLE records
      # (ID INTEGER PRIMARY KEY AUTOINCREMENT,
       # company           TEXT    NOT NULL,
       # keyword            INT     NOT NULL,
       # filename        CHAR(50),
       # date_found        DATETIME);''')

2 个答案:

答案 0 :(得分:3)

您可以将连接用作上下文管理器。这将正确终止连接,包括提交。

import sqlite3
from datetime import datetime
company = 'fghjk'
keyword = 'awesome'
filename = 'test.txt'
date_found = datetime.now()
conn = sqlite3.connect('test.db')
first = False

# use context manager here!!
with conn:
    c = conn.cursor()
    if first:
        conn.execute('''CREATE TABLE records
            (ID INTEGER PRIMARY KEY AUTOINCREMENT,
            company           TEXT    NOT NULL,
            keyword            INT     NOT NULL,
            filename        CHAR(50),
            date_found        DATETIME);''')

    for i in range(0,4):
        insert_query = "INSERT into records (company,keyword,filename,date_found) values (?,?,?,?)"
        c.execute(insert_query, [company,keyword,filename,date_found])

    select_query  = "SELECT * FROM records"
    c.execute(select_query)
    res = c.fetchall()
    print res
    for i in res:
        for b in i:
        print b

答案 1 :(得分:2)

问题似乎是您没有将数据提交到数据库。

每次打开数据库时,都会输入4行,然后打印它们,然后在不提交更改的情况下销毁光标和连接。

完成所有插入操作后调用conn.commit()将解决此问题。 IIRC,表创建在运行后立即自动提交,这就是它保存在数据库中的原因。