You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python操作SQLite3添加数据时出现语法错误求助

问题原因与解决方案

直接触发语法错误的原因

你的add_skill函数中,第一条SQL查询语句存在拼写错误:

cr.execute(f"select name form skills where name = {sk} and id = {uid}")

这里的form是笔误,正确的SQL关键字应为from。SQL解析器无法识别form这个无效关键字,因此抛出syntax error near "skills"的报错。

额外潜在问题与完整修复

除了拼写错误,代码还存在两个必须修正的问题:

  1. 字符串未加引号导致的语法错误:直接拼接字符串变量sk会生成name = Python这类SQL语句,SQL会把Python当作关键字而非字符串值,同样触发语法错误。
  2. SQL注入风险:将用户输入直接拼接进SQL语句,存在被恶意注入的安全隐患。

修复后的add_skill函数代码

使用SQLite的参数化查询(用?作为占位符)解决上述问题,同时修正拼写错误:

def add_skill():
    sk = input("Write skill name: ").strip().capitalize()

    # 修正form为from,使用参数化查询
    cr.execute(
        "select name from skills where name = ? and id = ?", (sk, uid)
    )
    result = cr.fetchone()

    if result is None:
        prog = input("Write skill progress: ").strip()
        # 参数化插入语句
        cr.execute(
            "insert into skills(name, progress, id) values(?, ?, ?)", (sk, prog, uid)
        )
        print("Data has been added.")

    else:
        print("This skill is already exist in database.")
        print("Do you want to update the progress of it ? (y/n)", end=" ")
        theA = input().strip().lower()

        match theA:
            case "y":
                Nprog = input("Write the new skill progress: ").strip()
                # 参数化更新语句
                cr.execute(
                    "update skills set progress = ? where name = ? and id = ?", (Nprog, sk, uid)
                )
                print("Data has been updated.")
            case "n":
                print("Quitting the app.")
                quitTheApp()
            case _:
                print("unexpected answer. sorry please try again.")

    commit_and_close()

关键修复点说明

  • 修正form为from,解决基础语法错误。
  • 所有SQL语句使用?作为占位符,将变量通过execute方法的第二个参数传入,由SQLite自动处理字符串转义和引号,彻底避免语法错误与SQL注入风险。

内容的提问来源于stack exchange,提问作者abd hadi Sakbani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:16:29