0

I'm using Angular, Flask and MySQL.connector to connect to a MySQL database:

This is my python flask code handling post requests inserting a new "movie":

@app.route("/addMovies", methods=['POST'])
def addMovies():
    cnx = mysql.connector.connect(user='root', database='MovieTheatre')
    cursor = cnx.cursor()
    insert_stmt = (
        "INSERT INTO Movie (idMovie, MovieName, MovieYear) "
        "VALUES (%d, %s, %d)"
    )

    post = request.get_json()
    #data = (post['idMovie'], post['MovieName'], post['MovieYear'])
    data = (100, 'Test', 2010) # test data 
    print(insert_stmt,data)
    cursor.execute(insert_stmt,data)
    cnx.commit()
    cnx.close()
    return data

I know its not my Angularjs, because my browser console says Internal Server Error (500) so I started printing out the insert statement handled by flask and mysql.connector:

('INSERT INTO Movie (idMovie, MovieName, MovieYear) VALUES (%d, %s, %d)', (100, 'Test', 2010))

Which seems correct.

However I keep getting

    "Wrong number of arguments during string formatting")
ProgrammingError: Wrong number of arguments during string formatting

===============================================================================

Thanks to the answers, its fixed, for those wondering this is what I switched my code to :

@app.route("/addMovies", methods=['POST'])
def addMovies():
    cnx = mysql.connector.connect(user='root', database='MovieTheatre')
    cursor = cnx.cursor()
    insert_stmt = (
        "INSERT INTO Movie (idMovie, MovieName, MovieYear) "
        "VALUES (%s, %s, %s)"
    )

    post = request.get_json()
    data = (post['idMovie'], post['MovieName'], post['MovieYear'])
    print(insert_stmt,data)
    cursor.execute(insert_stmt,data)
    cnx.commit()
    cnx.close()
    return data
3
  • you don't even need to call str() manually since the type conversion is the task of the cursor.execute method Commented Dec 3, 2016 at 19:59
  • ok true will remove that then Commented Dec 3, 2016 at 20:08
  • however then i get this error: TypeError: 'int' object is not callable Commented Dec 3, 2016 at 20:11

2 Answers 2

1

Check the docs, it says the cursor.execute() method converts things as necessary to something the database understands. It seems you are supposed to use only %s placeholders in your string and let everything else on the execute method.

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

Comments

1

SQL parameter substitution is not the same as string formatting. You should always use %s, even for integers.

Comments

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.