Reputation: 25
i need to create an sqlite table with the name of a global string variable, but i cant seem to find a way to insert the variable to the CREATE TABLE command.
is there a way to do so, or after creating a table with a placeholder name rename it to the variable?
the variable is an user input so i cannot name it in advance.
im coding in python.
Upvotes: 0
Views: 309
Reputation: 3833
F-strings like the one in Stefan's answers are great, and you can find a lot of use cases when working with SQL queries. Just be aware f-strings are available starting from Python 3.6 - if you are on an older version you will need to use the old %-formatting or str.format() methods, or simple string concatenation as already noted
Upvotes: 0
Reputation: 515
import sqlite3
con = sqlite3.connect(':memory')
cur = con.cursor()
TABLE_NAME = 'table_name'
cur.execute(f'CREATE TABLE {TABLE_NAME} (ID INTEGER PRIMARY KEY,
NAME VARCHAR(200))')
And yes, that also works with ALTER TABLE
.
Upvotes: 2