将用户输入插入.db时出现sqlite错误消息

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

当我运行flask时,我收到以下错误消息。

sqlite3.OptionalError: near "years": syntax error

错误消息放置在“cursor.execute(query1)”中

但是,我不使用“年”这个词,我在网上搜索过,但找不到任何建议。因此,我不知道我做错了什么。请问有人可以给我提示吗?

我尝试将未输入的用户插入到我的数据库表中。

我的代码是:

if request.method == "POST":
        b = request.form.get("bathtube")
        bath = request.form["bath"]
        di = request.form.get("dish")
        d = request.form["dishwasher"]
        wm = request.form.get("washing_machine")
        was = request.form["was"]
        wc = request.form["wc"]
        s = request.form["shower"]
        wa = request.form["water_use"]
        connection = sqlite3.connect('project.db')
        cursor = connection.cursor()



        query1 = "INSERT INTO water_use (user_id, bathtube, wc, washing_maschine, dishwasher,  wash_time, shower_time) VALUES ({user_id}, {bath}, {wc}, {wm}, {d}, {was}, {s}) WHERE user_id = :user_id".format(
            user_id=session["user_id"],
            bath=bath,
            wc=wc,
            wm=wm,
            d=d,
            was=was,
            s=s)

        cursor.execute(query1)
        connection.commit()

我的桌子是:

CREATE TABLE IF NOT EXISTS "water_use" (
    "user_id"   int,
    "bathtube"  int,
    "shower"    int,
    "wc"    int,
    "washing_maschine"  int,
    "dishwasher"    int,
    "wash"  int,
    "timestamp" timestamp,
    "wash_time" int,
    "shower_time"   int,
    "total" int,
    CONSTRAINT "id" FOREIGN KEY("user_id") REFERENCES "users"("id"),
    PRIMARY KEY("user_id")
);
database sqlite flask input
1个回答
0
投票

您应该始终使用占位符而不是字符串格式将Python值绑定到SQL语句,以避免SQL注入攻击

insert_statement = """
INSERT INTO water_use 
    (user_id, bathtube, wc, washing_maschine, dishwasher,  wash_time, shower_time)
VALUES 
    (?, ?, ?, ?, ?, ?, ?)
"""

values = (session["user_id"], bath, wc, wm, d, was, s)

cursor.execute(query1, values)
© www.soinside.com 2019 - 2024. All rights reserved.