2
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

1

2 Answers 2

9

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')
Sign up to request clarification or add additional context in comments.

6 Comments

... which is documented in more detail on this page: docs.python.org/release/2.6/library/sqlite3.html
i can persist into the database if i use %s placeholder in sqlite3. But will it be datetime.datetime when i retrieve
@Abdul Kader I added example session for sqlite3 and python. And you can't retrieve datetime object back from SQLite database without parsing because there is no datetime type in SQLite and datetime object will be stored as text.
I actully it stores as a unicode object. I want it to store as a datetime.datetime object. You can have a look here stackoverflow.com/questions/4272908/…
Check out this section of the documentation: docs.python.org/release/2.6/library/… But this example doesn't work for me. And you can also create converters yourself: docs.python.org/release/2.6/library/…
|
1

The error is self-speaking.

The string interpolation fails because you are passing two parameters to the INSERT string but there is only one %s placeholder. What do you want with '?' here.

Perhaps you ant

cur.execute('INSERT....', token, expires)

??

1 Comment

I want to persist datetime object.. Which placeholder i should use so that i comes as datetime object not as string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.