当我尝试在python中向SQLite3数据库添加数据时发生错误

mfuanj7w  于 11个月前  发布在  SQLite
关注(0)|答案(1)|浏览(119)

我已经创建了一个应用程序来显示,添加,删除和更新技能在数据库中使用Python和SQLite 3.在应用程序内部我使用函数方法.我使用的算法是:
1.为用户打印说明
1.等待用户输入他想要的操作
1.使用他的输入进入函数

# check if command is exist
    if user_input in commands_list:
        print(f"the command {user_input} founded")
        if user_input == "s":
            show_skills()
        elif user_input == "a":
            add_skill()
        elif user_input == "d":
            delete_skill()
        elif user_input == "u":
            update_skill()
        else:
            quitTheApp()
    else:
        print(f"Sorry the command \"{user_input}\" is not exist.")

字符串
1.函数add_skills()首先询问技能名称以添加它,但在此之前它检查它是否存在于数据库中,如果存在则正常添加,否则它告诉用户该技能已经存在并询问他是否要更改进度。这是add函数

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

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

        if result == None:
            prog = input("Write skill progress: ").strip()
            cr.execute(
                f"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(
                        f"update skills set progress = '{Nprog}' where name = '{sk}' and id = '{uid}'")
                    print("Data has been updated.")
                case "n":
                    print("Quitting the app.")
                    quitTheApp()
                case _:
                    print("unexpacted answer .sorry please try again.")

        commit_and_close()


因此,当我在终端中使用add_skills函数测试应用程序时,它只显示错误。我在终端中输入“a”命令以使用add函数,然后我输入一个名称,它在数据库中不存在,它显示此错误:near "skills": syntax error

ehxuflar

ehxuflar1#

你的SQL语句中有错别字:

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

字符串

  1. form应该是from
  2. {sk}没有用单引号括起来(')。
    更正后的行应为:
cr.execute(f"select name from skills where name = '{sk}' and id = '{uid}'")


虽然这应该可以工作,但我建议使用参数化查询来减少SQL注入的风险。此外,为了更好的可读性,编写SQL关键字是一个很好的做法。所以我建议:

cr.execute("SELECT name FROM skills WHERE name = ? AND id = ?", (sk, uid))

相关问题