简体   繁体   中英

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. 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. 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.

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, ? . Most other Python DB-APIs use %s for placeholders (not to be confused with the outmoded string modulo format symbol).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM