代码如下。如何按变量值?
替换[table, url]
?
预期的SQL命令为select * from OTHER_URL where url="http://a.com/a.jpg"
此SQL命令在sqlite3命令行界面上不会发生错误。
import sqlite3
from contextlib import closing
dbname = "ng.db"
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS OTHER_URL (url TEXT)")
conn.commit()
table = "OTHER_URL"
url = "http://a.com/a.jpg"
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
c.execute('select * from ? where url="?"', [table, url])
print c.fetchone()
答案 0 :(得分:2)
这里有两个错误。首先,您不能对表名(或列名)使用参数替换,仅用于值。您需要将字符串插值用于其他任何内容。
其次,你不需要在value参数周围引用;替代将照顾到这一点。
所以:
from datetime import datetime
with open("file.txt", mode="r+") as file1:
opened = datetime.now()
# do stuff with file
duration = datetime.now() - opened
print('File opened for {}'.format(duration.total_seconds()))