创建表名作为变量的正确语法是什么?

问题描述 投票:0回答:1

用户可以生成一个表格来对歌曲进行排名。它检查是否已有用户的排名系统,如果没有,则创建一个新表。我希望系统名称与用户 ID 相关联。

@app.route("/setup", methods=["GET", "POST"])
def setup():
    if request.method == "POST":
        user_id = str(session["user_id"])
        system_info = ()

        # Find or create system table
        while not system_info:
            cur.execute("SELECT system_name, ready, modified FROM systems WHERE user_id = ?", user_id)
            system_info = cur.fetchone()
            if not system_info:
                system_name = "system" + user_id
                cur.execute("INSERT INTO systems (user_id, system_name) VALUES (?, ?)", (user_id, system_name))
                cur.execute(
                    """
                    CREATE TABLE ? (
                    attribute_name TEXT NOT NULL,
                    type TEXT NOT NULL,
                    min INTEGER NOT NULL DEFAULT(0),
                    max INTEGER NOT NULL DEFAULT(0),
                    length_depend BOOLEAN DEFAULT(FALSE)
                    )
                    """
                    , system_name)

我从创建表格的行得到这个:

sqlite3.OperationalError:“?”附近:语法错误

我尝试了

system_name = str("system" + user_id")
并将
system_name
以元组格式作为
cur.execute
的最终参数。我在两次更改时都收到相同的错误消息。

python sql sqlite create-table sqlite3-python
1个回答
0
投票

查询中的表名不支持占位符。根据我的理解,鉴于

system_name
及其组件不是用户提供的,这是安全的:

if request.method == "POST":
    user_id = str(session["user_id"])
    system_info = ()

    # Find or create system table
    while not system_info:
        cur.execute("SELECT system_name, ready, modified FROM systems WHERE user_id = ?", user_id)
        system_info = cur.fetchone()
        if not system_info:
            system_name = "system" + user_id
            query = """
                CREATE TABLE {} (
                attribute_name TEXT NOT NULL,
                type TEXT NOT NULL,
                min INTEGER NOT NULL DEFAULT(0),
                max INTEGER NOT NULL DEFAULT(0),
                length_depend BOOLEAN DEFAULT(FALSE)
                )
                """.format(system_name)
            cur.execute("INSERT INTO systems (user_id, system_name) VALUES (?, ?)", (user_id, system_name))
            cur.execute(query)
© www.soinside.com 2019 - 2024. All rights reserved.