1

Hello I was following Python MYSQL update statement and managed to produce this code for my programme's SQL Update with variables function:

def editInfo(start, userName):
    newFavGenre = input("Enter your favourite genre")
    newFavArtist = input("Enter your favourite artist")
    ## userName is a global variable
    con = lite.connect(db)
    cur = con.cursor()
    cur.execute ("""
    UPDATE users
    SET favGenre=%s, favArtist=%s
    WHERE username=%s
""", (newFavGenre, newFavArtist, userName))
    results = cur.fetchall()
    return result
    mainmenu()

And keep expericiencing this error code:

sqlite3.OperationalError: near "%": syntax error

Any ideas where I am going wrong?

Skam
  • 7,298
  • 4
  • 22
  • 31

1 Answers1

2

It appears the post you are looking at is for MySQL and I conjecture that you're using the sqlite3 python interface based on your error.

Looking at the sqlite3 docs...

cur.execute("""
    UPDATE users
    SET favGenre=%s, favArtist=%s
    WHERE username=%s
""", (newFavGenre, newFavArtist, userName))

Should instead be

cur.execute("""
    UPDATE users
    SET favGenre=?, favArtist=?
    WHERE username=?
    """, (newFavGenre, newFavArtist, userName))

You could also use their named style which instead of taking a tuple takes a dictionary.

cur.execute("""
    UPDATE users
    SET favGenre=:genre, favArtist=:artist
    WHERE username=:username
""", {'genre':newFavGenre, 'artist': newFavArtist, 'username':userName})
Skam
  • 7,298
  • 4
  • 22
  • 31