Question

after searching untill madness, i decided to post a question here. I try to create a sqlite3 database where i'd like to make use of the secure variable substituation function of the cursor.execute(SQL, param) function. My function goes like this:

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import sqlite3

def create():
    values = ("data")
    sql = "CREATE TABLE IF NOT EXISTS ? ( name TEXT, street TEXT, time REAL, age INTEGER )"

    con = sqlite3.connect("database.db")
    c = con.cursor()
    c.execute(sql, values)
    con.commit()
    c.close()
    con.close()

if __name__ = "__main__":
    create()

I know that the first argument should be the sql command in form of a string and the second argument must be a tuple of the values which are supposed to be substituted where the ? is in the sql string. However, when i run the file it returns the following error:

$ ./test.py 

Traceback (most recent call last):
  File "./test.py", line 21, in <module>
    create()
  File "./test.py", line 14, in create
    c.execute(sql, values)
sqlite3.OperationalError: near "?": syntax error

This also happens when paramstyle is set to named (e.g. the :table form). I can't spot a syntax error here, so i think that the problem must be caused somewhere in the system. I tested it on an Archlinux and Debian install, both post me the same error.

Now it is up yo you, as I have no idea anymore where to look for the cause.

Was it helpful?

Solution

SQL parameters can only apply to insert data, not table names. That means parameters are not even parsed for DDL statements.

For that you'll have to use string formatting:

sql = "CREATE TABLE IF NOT EXISTS {} ( name TEXT, street TEXT, time REAL, age INTEGER )".format(*values)

OTHER TIPS

As I understand, your parameter is the table name?

so your command would be

tbl = 'my_table'
sql = "CREATE TABLE IF NOT EXISTS '%s' ( name TEXT, street TEXT, time REAL, age INTEGER )" % tbl
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top