[英]sqlite3.OperationalError: near "<": syntax error: Issue with sql in python formatting?
I'm doing a Software Engineering Project for one of my final courses as a Comp Sci major and I'm getting hungup on this particular error while I'm trying to do my data/unit testing of the methods before merging my methods with our teammates GUI.我正在为我作为 Comp Sci 专业的最后一门课程做一个软件工程项目,当我尝试在将我的方法与我们的方法合并之前对方法进行数据/单元测试时,我对这个特定的错误感到困惑队友GUI。 Anyone who can help me solve this issue is my hero
任何能帮助我解决这个问题的人都是我的英雄
class Student:
def __init__(self, StudentID, StudentName, conn: sql.Connection, curs: sql.Cursor):
self.StudentID = StudentID
self.StudentName = StudentName
def addStudent(self, curs: sql.Cursor):
query = f"""INSERT INTO Student
(StudentID, StudentName)
VALUES ({self.StudentID},{self.StudentName})"""
curs.execute(query)
As commented, consider parameterization.如评论所述,考虑参数化。 Right now your string formatting does not enclose potential string values in single quotes in
VALUES
clause.现在,您的字符串格式不会在
VALUES
子句中将潜在的字符串值括在单引号中。 With parameterization which involves placeholders in a prepared SQL statement and binding values in the execution call, you do not need to worry about such quotes.使用涉及准备好的 SQL 语句中的占位符和执行调用中的绑定值的参数化,您无需担心此类引号。
def addStudent(self, curs: sql.Cursor):
# PREPARED STATEMENT (NO VARIABLES)
query = """INSERT INTO Student (StudentID, StudentName)
VALUES (?, ?)
"""
# EXECUTE BY BINDING PARAMS
curs.execute(query, [self.StudentID, self.StudentName])
Above assumes you are using the sqlite3
DB-API which uses qmark placeholder, ?
以上假设您使用的是使用 qmark 占位符的
sqlite3
DB-API ?
. . Most other Python DB-APIs use
%s
for placeholders (not to be confused with the outmoded string modulo format symbol).大多数其他 Python DB-API 使用
%s
作为占位符(不要与过时的字符串模格式符号混淆)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.