Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store python datetime object in sqlite3

Tags:

python

sqlite

token=uuid.uuid4().bytes.encode("base64")
expires=datetime.now()+timedelta(days=1)
print token
print expires
con = sqlite3.connect(dbpath,detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute(
    "INSERT INTO token VALUES ('%s', ?)" % 
      (token,expires))
a=cur.fetchone()
con.commit()
con.close() 

Table CREATE TABLE token (token varchar(255),expires DATE);

Error TypeError: not all arguments converted during string formatting

like image 653
Abdul Kader Avatar asked Feb 12 '26 06:02

Abdul Kader


1 Answers

Never use % operator with SQL - it can lead to SQL injection. Fix your execute statement like this:

cur.execute("INSERT INTO token VALUES (?, ?)", (token,expires))

Actually there is another one problem: you can't use cur.fetchone() after INSERT.

Full example:

$ sqlite3 test.db
sqlite> create table token (token text primary key, expires text);

$ python
>>> import sqlite3
>>> from datetime import datetime, timedelta
>>> from uuid import uuid4
>>> token = uuid4().bytes.encode("base64")
>>> expires = datetime.now() + timedelta(days=1)
>>> conn = sqlite3.connect("test.db")
>>> cur = conn.cursor()
>>> cur.execute("INSERT INTO token VALUES (?, ?)", (token, expires))
<sqlite3.Cursor object at 0x7fdb18c70660>
>>> cur.execute("SELECT * FROM token")
<sqlite3.Cursor object at 0x7fdb18c70660>
>>> cur.fetchone()
(u'9SVqLgL8ShWcCzCvzw+2nA==\n', u'2011-04-18 15:36:45.079025')
like image 167
hdima Avatar answered Feb 14 '26 21:02

hdima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!