0

i have a strange behavior with a very simple query in sqlite (python sqlite3)

Here is a query which works

cursor = self.con.cursor()
cursor.execute("SELECT * FROM vpro1 ORDER BY :orderby DESC LIMIT 1", {"table": "vpro1", "orderby": self.unit_timestamp})

But this one throw me an error

cursor = self.con.cursor()
cursor.execute("SELECT * FROM :table ORDER BY :orderby DESC LIMIT 1", {"table": "vpro1", "orderby": self.unit_timestamp})

The Exception is

sqlite3.OperationalError: near ":table": syntax error

So when i try to use the qmark for table name it throws an error, if i hardcode it in the query, it works, the :orderby works whatever i use (qmark, hardcoded, named)... Same behavior with qmark style (?,? with a tuple)

Thanks for your advice !

Gehasia
  • 33
  • 5

1 Answers1

2

You cannot use the DB API to complete table names. I'm not sure what the reason for this is, but I've encountered this same problem in the past. It does not work in SQLite or MySQL and probably others.

See Donald Miner's answer to another question for a workaround.

def scrub(table_name):
    return ''.join( chr for chr in table_name if chr.isalnum() )

scrub('); drop tables --')  # returns 'droptables'

Then pass this in as a format string.

table = "vpro1"
cursor.execute("SELECT * FROM {0} ORDER BY :orderby DESC LIMIT 1".format(scrub(table)), {"orderby": self.unit_timestamp})
Community
  • 1
  • 1
Fredrick Brennan
  • 7,079
  • 2
  • 30
  • 61
  • Thanks for this solution ! I've searched but never found the Donald Miner's post, so thanks for your (and his) tip ! – Gehasia Jan 18 '13 at 15:16