简体   繁体   中英

Python2.7 - SQLite3 library outputs error message “sqlite3.OperationalError: near ”?“: syntax error”

Code is follow. How to get replaced ? by value of variables [table, url] ?

Expected SQL command is select * from OTHER_URL where url="http://a.com/a.jpg"

This SQL command occurs no error on the sqlite3 command line interface.

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()

There are two errors here. Firstly, you can't use parameter substitution for table names (or column names), only for values. You need to use string interpolation for anything else.

Secondly, you don't need quotes around the value parameter; the substitution will take care of that.

So:

c.execute('select * from {} where url=?'.format(table), [url])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM