Search code examples
pythonsqliteinstance-variables

Using instance variables in SQLite3 update?


Ok so basically I'm trying to update an existing SQLite3 Database with instance variables (typ and lvl)

#Set variables
typ = 'Test'
lvl = 6

#Print Databse
print("\nHere's a listing of all the records in the table:\n")
for row in cursor.execute("SELECT rowid, * FROM fieldmap ORDER BY rowid"):
    print(row)

#Update Info
sql = """
UPDATE fieldmap
SET buildtype = typ, buildlevel = lvl
WHERE rowid = 11
"""

cursor.execute(sql)

#Print Databse
print("\nHere's a listing of all the records in the table:\n")
for row in cursor.execute("SELECT rowid, * FROM fieldmap ORDER BY rowid"):
    print(row)

As an Error I'm getting

sqlite3.OperationalError: no such column: typ

Now I basically know the problem is that my variable is inserted with the wrong syntax but I can not for the life of me find the correct one. It works with strings and ints just fine like this:

sql = """
UPDATE fieldmap
SET buildtype = 'house', buildlevel = 3
WHERE rowid = 11
"""

But as soon as I switch to the variables it throws the error.


Solution

  • Your query is not actually inserting the values of the variables typ and lvl into the query string. As written the query is trying to reference columns named typ and lvl, but these don't exist in the table.

    Try writing is as a parameterised query:

    sql = """
    UPDATE fieldmap
    SET buildtype = ?, buildlevel = ?
    WHERE rowid = 11
    """
    
    cursor.execute(sql, (typ, lvl))
    

    The ? acts as a placeholder in the query string which is replaced by the values in the tuple passed to execute(). This is a secure way to construct the query and avoids SQL injection vulnerabilities.