sqlite3.operational错误:无法识别的标记:“01T00”Python日期戳

2024-10-01 04:49:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在将值插入SQLite数据库时遇到问题。我从挪威议会网站data.stortinget.no下载的数据。我得到的错误是:sqlite3.operational错误:无法识别的令牌:“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上面打印的消息是: 编号:2009-2013 fra:2009-10-01T00:00至: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手册,似乎支持这种格式,所以我想知道问题是从哪里来的。


Tags: noiddataget错误pageelprint
1条回答
网友
1楼 · 发布于 2024-10-01 04:49:46

正确的方法是使用参数化查询。
示例:

cur.execute("""INSERT INTO perioder(fra, id, til) 
               VALUES (?,?,?);""", (fra, per_id, til))

每个数据库驱动程序都有一个特定的参数“style”。
对于SQLite,参数样式是?

还要注意,参数值作为第二个参数传递给execute()
使用字符串插值会使您容易受到各种引用问题(比如您在这里遇到的问题)和SQL注入攻击的可能性。

有关详细信息,请阅读the DB-APIdatabase programming wiki

相关问题 更多 >