Skip to content
Advertisement

In python, can we set table name as a variable using Sqlite3?

For example:

import Sqlite3
def ChangeTable(c,a):
    c.execute('''DELETE FROM MY_TABLE WHERE id = ?''',(a,))

This way I can change the value of a and process the database with a function in python. But how can I do something similar with Table names? This way I can use one function to handle different tables.

Advertisement

Answer

Parsing in table names is made to not work intentionally, since dynamically using table names in SQL queries is generally a bad idea. If you’re in a situation where you end up dynamically wanting to do stuff with table names, you should think about redesigning your database and make it relational. It’s hard to give specific advice about how to do this in your case, since we don’t know how your database is arranged.

The other answer involves using string formatting in SQL queries. This is very bad coding practice, since it makes your code vulnerable to SQL injection. The sqlite documentation says to never do this, in fact. You don’t want to have a Bobby Tables situation on your hands.

Advertisement