0

I'm trying to make a function to drop all the tables in the current database. This is what I have:

def drop_tables (self):
    cur.execute ("SELECT name FROM sqlite_master WHERE type='table';")
    tlist = cur.fetchall()
    with conn:
        for t in tlist:
            cur.execute ('DROP TABLE ?;', t[0])

Which yields the following error:

File "/storage/sdcard0/com.hipipal.qpyplus/.last_tmp.py", line 170, in drop_tables
cur.execute ('DROP TABLE ?;', t[0])
sqlite3.OperationalError: near "?": syntax error

It's a sqlite3 error, not a python error. Can I not have the cursor substitute like this? Is there any other way to achieve this; other then deleting the database? (And I don't know if the "with" statement is required for a DROP, but I get the error regardless)

Thank you

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117

1 Answers1

1

You cannot use parameters to specify any SQL keyword or database entity name. You can only use them in place of column values. You will need to construct the DROP TABLE command as an SQL string and pass the unparameterized string as the SQL command. If the table name originates outside your application, make sure to sanitize it!

Larry Lustig
  • 49,320
  • 14
  • 110
  • 160
  • I didn't even think of just preformatting it as a string -_-. You can tell I'm over tired. And it can't be malicious as what I'm trying to insert is the name of a table, so any injected commands would have to be in the form of a created table name. Plus, even if that is possible, the db is a save for a game I'm making, so I couldn't care less at this point. Thank you! – Carcigenicate May 14 '14 at 01:24