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.
asked Nov 19, 2015 at 20:28
Bijan
8,83622 gold badges107 silver badges165 bronze badges
-
2table names cannot be parameterized. you can use python string formatting to do thatR Nar– R Nar2015年11月19日 20:33:58 +00:00Commented Nov 19, 2015 at 20:33
2 Answers 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.
answered Nov 19, 2015 at 20:32
Larry Lustig
51.2k16 gold badges119 silver badges173 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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()
Pang
10.2k146 gold badges87 silver badges126 bronze badges
answered Nov 19, 2015 at 20:39
karastojko
1,1819 silver badges14 bronze badges
2 Comments
Bijan
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
karastojko
My bad. Yes, as stated above - parametrized queries are for DML but not for DDL queries.
default