Syntax error in database (dictionary) (Python) [closed]

I am trying to insert the last name value into the “test” table, but I am getting an exception. My problem is that I cannot insert the string representation of the dictionary into the table.

Exception thrown: OperationalError
next to "Surname": syntax error

My code:

con = sql.connect('test.db')
with con:
    cur = con.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS `test` (`name` STRING, `surname` STRING)")
    name = input("Namen> ")
    surname = str({'Surname': 1})
    cur.execute(f"INSERT INTO `test` VALUES ('{name}', '{surname}')")

    con.commit()
    cur.close()

Answer

Using placeholders will free you from the need to sanitize your input (and muck around with quotes), as well as protecting you from SQL injection attacks.

By the line con = sql.connect('test.db') I’m guessing that you’re using sqlite3. If you aren’t the same principle should still hold, but the exact syntax for the placeholder may vary:

cur.execute("INSERT INTO `test` VALUES (?, ?)", (name, surname))