我已经使用 python 和 SQLite 3 创建了一个应用程序来显示、添加、删除和更新数据库中的技能。 在应用程序内部我使用了函数方法。 我使用的算法是:
# 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.")
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”命令来使用添加功能,然后输入一个以前在数据库中不存在的名称,它向我显示此错误:
near "skills": syntax error
您的 SQL 语句中有拼写错误:
cr.execute(f"select name form skills where name = {sk} and id = {uid}")
form
应该是 from
。{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))