0

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.

4
  • 1
    You can use simple string concatenation. "CREATE TABLE " + tablename Commented May 18, 2021 at 17:13
  • 1
    It's not really clear what you are after — how are you going to reference that global variable if not by name and if you know the name, why can't you use a string? Can you add a little code to clarify? Commented May 18, 2021 at 17:13
  • the variable is created by user input, sorry for not clarifying i'll update the post Commented May 18, 2021 at 17:15
  • 1
    Be careful to sanitise the user input before you glue it into an SQL statement. Commented May 18, 2021 at 17:18

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.