0

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)
1
  • Please read on parameterization. In Python and all general-purpose programming languages, developers should avoid interpolating or concatenating values to SQL statements, specifically here with f-strings. Commented Nov 25, 2021 at 16:21

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

I concur. Just to add a bit: the < likely came from either StudentID or StudentName. @Demigas Try posting an example of the input.
And @carrvo, with params, if that symbol is in StudentName it will render in binded string value as is without error. If StudentID is an integer, SQLite may throw a different error due to non-number characters. Without params or quotes, < becomes a structural part of SQL statement and not part of literal value.
Hello! Thank you for the awesome feedback. I tried your methodology and now it's telling me "sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type."
Update: Now its not adding to the database but I'm not getting any errors.
Are you running committing after execute: connection.commit()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.