Home > OS >  Cannot insert integer to MySQL in python
Cannot insert integer to MySQL in python

Time:09-06

In my flask application, I cannot insert user_id which I get from request.form and it is an integer to MySQL. Here is my code:

from flask import Flask, jsonify, render_template
from flask import request
import socket
from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_HOST'] = '192.168.0.101'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PORT'] = '3307'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'msblog_users'
 
mysql = MySQL(app)   

@app.route("/create_post", methods = ['POST', 'GET'])
def create_post():
    if request.method == 'GET':
        return "You can only send post requests here!"

    if request.method == 'POST':
        user_id = request.form.get('user_id')
        message = request.form.get('message')
        cursor = mysql.connection.cursor()
        cursor.execute('''INSERT INTO posts (user_id, post)VALUES (%s, %s)''', (int(user_id), message))
        mysql.connection.commit()
        cursor.close()
        return "Done"

I get the following error:

TypeError: 'str' object cannot be interpreted as an integer

What should I do? I did lots of search but so far nothing!

CodePudding user response:

The error comes from the int(user_id) part, specifically due to the value being None. You should first make sure it is a valid integer:

try:
    user_id = int(request.form.get('user_id'))
except (ValueError, TypeError):
    return <error 400>

CodePudding user response:

The %s stands for string, if you want you want that parameters to be an integer, make it %i.

INSERT INTO posts (user_id, post)VALUES (%i, %s) ....

If the column post is a string / text column (varchar probably) you should also quote it as such.

cursor.execute("INSERT INTO posts (user_id, post) VALUES (%i , '%s')" % (1, 'string value')

By the way, this is the old way of formatting strings

The new way is doing this:

cursor.execute("INSERT INTO posts (user_id, post) VALUES ({}, '{}')".format(1, 'string value')

Or you can name the parameters:

"INSERT INTO posts (user_id, post) VALUES ({id}, '{str}')".format( str='string value',id=1)
  • Related