Demigas
Demigas

Reputation: 3

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)

Upvotes: 0

Views: 1843

Answers (1)

Parfait
Parfait

Reputation: 107567

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

Upvotes: 1

Related Questions