[英]Store python datetime object in sqlite3
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); 表 CREATE TABLE标记(标记varchar(255),到期日期DATE);
Error TypeError: not all arguments converted during string formatting 错误 TypeError:并非在字符串格式化期间转换所有参数
Never use %
operator with SQL - it can lead to SQL injection. 永远不要将
%
运算符与SQL一起使用 - 它可以导致SQL注入。 Fix your execute
statement like this: 像这样修复你的
execute
语句:
cur.execute("INSERT INTO token VALUES (?, ?)", (token,expires))
Actually there is another one problem: you can't use cur.fetchone()
after INSERT
. 实际上还有一个问题:在
INSERT
之后你不能使用cur.fetchone()
。
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')
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. 字符串插值失败,因为您将两个参数传递给INSERT字符串,但只有一个%s占位符。 What do you want with '?'
你想要什么'?' here.
这里。
Perhaps you ant 也许你是蚂蚁
cur.execute('INSERT....', token, expires) cur.execute('INSERT ....',token,expires)
?? ??
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.