【发布时间】:2021-11-12 20:21:56
【问题描述】:
我在将值插入 SQLite 数据库时遇到问题。我从挪威议会网站 data.stortinget.no 下载的数据。我得到的错误是: sqlite3.OperationalError: unrecognized token: "01T00"
这是发生错误的方法:(我知道这个摘录中的缩进错误)
def get_perioder(cur):
DOK = "stortingsperioder"
try:
page = urllib2.urlopen(SITE+DOK)
except:
print "Failed to fetch item "+DOK
if page:
tree = ElementTree.parse(page)
root = tree.getroot()
top = list(root)[2]
elements = list(top)
for el in elements:
fra = el.find('{http://data.stortinget.no}fra').text
per_id = el.find('{http://data.stortinget.no}id').text
til = el.find('{http://data.stortinget.no}til').text
print "id: %s fra: %s til: %s" % (per_id, fra, til)
cur.execute("INSERT INTO perioder(fra, id, til) VALUES(%s,%s,%s)" % (fra, per_id, til))
else:
print "Could not load page: "+DOK
cur.execute 上面的 print 打印的消息是: id: 2009-2013 fra: 2009-10-01T00:00:00 til: 2013-09-30T23:59:59 整个错误跟踪是:
BigMac:Stortingsdata ola$ python getBasicData.py
id: 2009-2013 fra: 2009-10-01T00:00:00 til: 2013-09-30T23:59:59
Traceback (most recent call last):
File "getBasicData.py", line 169, in <module>
get_perioder(cur)
File "getBasicData.py", line 26, in get_perioder
cur.execute("INSERT INTO perioder(fra, id, til) VALUES(%s,%s,%s)" % (fra, per_id, til))
sqlite3.OperationalError: unrecognized token: "01T00"
我参考了SQLite手册,似乎支持格式,所以我想知道问题出在哪里。
【问题讨论】:
-
你没有用引号
INSERT INTO perioder(fra, id, til) VALUES('%s',%s,'%s')传递日期? -
您插入的是
VALUES(2009-2013, 2009-10-01T00:00:00, 2013-09-30T23:59:59)。你明白为什么这是错误的,对吧?您刚刚插入了等价的VALUES(-4, -1-01T00:00:00, 2004-30T23:59:59),这显然是一个语法错误,因为01T00不能从-1中减去。只需正确使用execute而不是进行字符串插值。 -
我现在明白了。我以为 %s 添加了所需的引号,但我错了。谢谢两位的帮助,现在可以了。当我运行代码时出现了另一个问题。它执行第一种方法,但不从附加方法中添加数据。我可以将游标传递给方法并添加数据,还是需要更多游标? (程序没有任何并发)