0

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

1 Answer 1

2

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

Comments

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.