Ad

Python Mysql Insert Error

- 1 answer

I keep getting the error information after running this line of code

query = ("INSERT INTO Movies" "(movie_id,movie_name,movie_year,duration,score,storyline,genre,poster)" 
    "VALUES (%(ID)s,%(name)s,%(year)s,%(runtime)s,%(rating)s,%(storyline)s,%(genre)s,%(links)s)")   #args = (ID,name,year,runtime,rating,storyline,genre,links) 
cursor.execute(query)
con.commit()

The format is from mysql document

the error message is

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%(ID)s,%(name)s,%(year)s,%(runtime)s,%(rating)s,%(storyline)s,%(genre)s,%(links)' at line 1
Ad

Answer

You are missing the query parameters:

cursor.execute(query, args)

where args, since you are using named parameters, has to be a dictionary where the keys should correspond to the parameter names:

args = {
    "name": "some name",
    "year": 1962,
    # ...
}

As a side note, you can put your query into a multi-line string for readability:

query = """
    INSERT INTO 
        Movies
        (movie_id, movie_name, movie_year, duration, score, storyline, genre, poster)
    VALUES 
        (%(ID)s, %(name)s, %(year)s, %(runtime)s, %(rating)s, %(storyline)s, %(genre)s, %(links)s)
"""
Ad
source: stackoverflow.com
Ad