0

I have the following code to create a table if it does not already exist in a database.

TABLE_NAME = 'Test'

sql = sqlite3.connect('DATABASE.db')
cur = sql.cursor()

cur.execute('CREATE TABLE IF NOT EXISTS ? (id TEXT)', [TABLE_NAME])
sql.commit()

But I keep getting sqlite3.OperationalError: near "?": syntax error

I have other code such as cur.execute('INSERT * INTO database VALUES(?,?)', [var1, var2]) that works fine.

1

2 Answers 2

2

That is correct, parameters cannot be used to substitute for database identifiers, only for values. You will have to build the SQL command, with the table name specified, as a string.

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

Comments

0

The following code creates the table

import sqlite3
sql = sqlite3.connect('DATABASE.db')
cur = sql.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS Test (id TEXT)')
sql.commit()

2 Comments

I know how to create a table. My problem is I wanted to create a table based on a variable using ? but that is apparently not possible
My bad. Yes, as stated above - parametrized queries are for DML but not for DDL queries.

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.