Sqlite和python时间戳

时间:2013-05-14 22:16:33

标签: python sqlite

我在python 2.4中有这个代码:

import datetime, time, sqlite
def metodo(date):
        conn = sqlite.connect('dataBase.db')
        c = conn.cursor()
        c.execute("INSERT INTO f values(?,?)", (3,date))
        conn.commit()
        conn.close()

end_date=datetime.datetime(2012, 10, 21, 0, 0)
print end_date

metodo(end_date)

和一个带有int和TIMESTAMP

的sqlite数据库
create table f(id int, time TIMESTAMP)

但我在python中获得了这个:

Traceback (most recent call last):
File "prueba.py", line 13, in ?
metodo(end_date)
File "prueba.py", line 6, in metodo
c.execute("INSERT INTO f values(?,?)", (3,date))
File "/usr/lib/python2.4/site-packages/sqlite/main.py", line 255, in execute
self.rs = self.con.db.execute(SQL % parms)
TypeError: not all arguments converted during string formatting

此代码运行良好。问题在于时间戳:

import datetime, time, sqlite
def metodo(date):
        conn = sqlite.connect('dataBase.db')
        c = conn.cursor()
        c.execute("INSERT INTO a values(%s)", date)
        conn.commit()
        conn.close()


metodo("stringTest")

和一个带有int和TIMESTAMP

的sqlite数据库
create table a(test text)

1 个答案:

答案 0 :(得分:1)

我认为你应该像这样参数化:

def metodo(date):
        conn = sqlite.connect('dataBase.db')
        c = conn.cursor()
        c.execute("INSERT INTO a values(%s)", (date,))
        conn.commit()
        conn.close()