Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t use variables for table names. You have to perform string concatenation or substitution. As an example, using an F-string (Python >= 3.6):

def change_table(table_name, id):
    c.execute(f'DELETE FROM {table_name} WHERE id = ?', (id,))

with more meaningful variable names…
Triple quoting is not required here but useful for multiline statements.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading