0

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.

4

2 回答 2

5

SQL 参数只能用于插入数据,不能用于表名。这意味着甚至没有为 DDL 语句解析参数。

为此,您必须使用字符串格式:

sql = "CREATE TABLE IF NOT EXISTS {} ( name TEXT, street TEXT, time REAL, age INTEGER )".format(*values)
于 2013-11-07T18:24:08.993 回答
0

据我了解,您的参数是表名?

所以你的命令是

tbl = 'my_table'
sql = "CREATE TABLE IF NOT EXISTS '%s' ( name TEXT, street TEXT, time REAL, age INTEGER )" % tbl
于 2013-11-08T13:17:45.693 回答