【发布时间】:2019-05-27 06:58:40
【问题描述】:
我正在尝试使用 Python 库 sqlite3 填写 SQLite 数据库。在这个例子中,这个想法只是从文件中读取数据并填充数据库,然而,虽然看起来正在创建表,但数据库并没有增长,也没有写入值。
我的代码如下:
import sqlite3
def update_db(c, key, val):
sql = ''' UPDATE atable SET f1 = ? WHERE id = ?; '''
c.execute(sql, (val, key))
def create_table(c):
sql = ''' CREATE TABLE atable (id text PRIMARY KEY, f1 integer DEFAULT 0); '''
c.execute(sql)
with sqlite3.connect('test.db') as conn:
c = conn.cursor()
create_table(c)
with open('file1.txt') as f1:
for line in f1:
l = line.strip().split()
update_db(c, l[0], int(l[1]))
conn.commit()
这段代码运行没有错误,但是当尝试使用 Python 查询这个数据库时:
with sqlite3.connect('test.db') as conn:
c = conn.cursor()
c.execute('SELECT * FROM atable;')
for row in c:
print(row)
或者在 SQLite 命令界面中:
$ sqlite3 test.db
SQLite version 3.8.10.2 2015-05-20 18:17:19
Enter ".help" for usage hints.
sqlite> SELECT * FROM atable;
sqlite> .tables
atable
sqlite>
输出始终为空(但看起来该表已正确创建)。我在这里做错了什么?
用于测试的“file1.txt”是这样的:
foo 2
bar 0
baz 1
【问题讨论】:
-
您正在尝试更新行;你确定你不是要插入一些行吗?
-
@khelwood,不确定,我现在正在学习 SQLite。这个想法是从可以共享(或不共享)相同密钥“id”的多个文件(不适合内存)中读取,因此更新 .对于每个键“id”(行),最终数据库应该有多个列。
-
如果您所做的只是更新,您的表将保持为空。 UPDATE 不添加行; INSERT 可以。
标签: python python-3.x sqlite