0

I have this small decorator function where I am going to find an unknown number of entries in a table:

def Deco(func):
     func
     conn = sqlite3.connect('/home/User/vocab_database/vocab.db')
     with conn:
         cur = conn.cursor()
         cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
         total = cur.fetchall()
         print "You have %d tables " % len(total)

       ## this line below, is where I wanted to use a formatted string ##
         cur.execute("SELECT * FROM %s") % total[0]
         entries = cur.fetchall()
         print "You have %d entries" % len(entries)

Then I get this error message:

Traceback (most recent call last):
  File "./database_trial.py", line 19, in <module>
    class Vocab:
  File "./database_trial.py", line 25, in Vocab
    @Deco        
  File "./database_trial.py", line 15, in Deco
    cur.execute("SELECT * FROM %s") % total[0]
sqlite3.OperationalError: near "%": syntax error

Does sqlite3 only accept ? operators? Or is there something I'm mucking up?

2
  • That's not string interpolation. Commented Aug 20, 2012 at 2:36
  • 1
    Another name for using the mod operator on strings. And harder to confuse with the format() method. Commented Aug 20, 2012 at 2:40

2 Answers 2

3

You're trying to replace metadata, so unfortunately a parametrized query won't work. You must use interpolation or the like here, but make sure that the value is sanitized; this is a possible vector for a SQL injection.

cur.execute("SELECT * FROM %s" % (total[0],))
Sign up to request clarification or add additional context in comments.

4 Comments

cur.execute("SELECT * FROM %s" % (total[0],)) returns error cur.execute("SELECT * FROM %s" % (total[0],)) sqlite3.OperationalError: near ")": syntax error
Then you have a problem in total[0].
I just had print out total[0] = (u'Words',) so I would have to use total[0][0]. To be clear though the ? wouldn't work in this case either way? Much Thanks for the help :)
Any field names, table names, etc ?
2

In the line cur.execute("SELECT * FROM %s") % total[0], you are applying the % operator to the result of the cur.execute call. I think you want to do the substitution inside the call, e.g., cur.execute("SELECT * FROM ?", (total[0],)).

2 Comments

You omitted the comma. It's (total[0],), not (total[0]).
cur.execute("SELECT * FROM ?", (total[0],)) sqlite3.OperationalError: near "?": syntax error even with the comma.

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.