Unable to run Mysql Insert command using Flask app

I have a flask app which is needed to insert data to db table which is mysql , so whatever port or host i give it is throwing me error like below .

mysql.connector.errors.InterfaceError

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:8016' (10061 No connection could be made because the target machine actively refused it)

So here is my code :

from flask import Flask
from flask import jsonify
import mysql.connector

app = Flask(__name__)

@app.route('/')
def hello():
    print("Just go inside ")
    return 'Atlast got inside Page'


@app.route('/insertdataToDBFile/<dbname>')
def writetodbfile(dbname):
    '''mydb = mysql.connector.connect(
        host="localhost",
        user="root",
        password=""
    )
    mycursor = mydb.cursor()

    mycursor.execute("CREATE DATABASE IF NOT EXISTS "+dbname)'''
    print("before connect")
    mydb = mysql.connector.connect(
        host="localhost",
        port="8016",
        user="root",
        password="",
        database = dbname
    )

    mycursor = mydb.cursor()
    '''mycursor.execute("CREATE TABLE IF NOT EXISTS Issues  (name VARCHAR(255), address VARCHAR(255))")'''
    print("before Insert")
    sql = "INSERT INTO Issue VALUES('Hi;llos','20120618 10:34:09 AM','kl','prod','20120618 10:34:09 AM','yes','yes','20120618 10:34:09 AM','yes','123','poem')"
    mycursor.execute(sql)

    mydb.commit()

    return (str(mycursor.rowcount) + " record inserted.")

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8015, debug=True)

Since DB and Table is already created i commented out those lines . it is currently deployed inside Windows remote server and also it prints before connect on to console . I don know whether that is the reason . Can anyone help me to figure out why this is happening

Answer

https://stackoverflow.com/a/54231402/15185285

The link above helped me find the answer you were looking for.

I had to do some minor tweaks to fit it to mysql functions that I made.

I’m posting below my code.

python code

##sql functions:

def create_server_connection(host_name, user_name, user_password,database_name):
    connection = None
    try:
        connection = mysql.connector.connect(
            host=host_name,
            user=user_name,
            passwd=user_password,
            database=database_name
        )
        #print("MySQL Database connection successful")
    except Error as err:
        print(f"Error: '{err}'")

    return connection

def execute_query(connection, query):
    cursor = connection.cursor()
    try:
        cursor.execute(query)
        connection.commit()
        #print("Query successful")
    except Error as err:
        print(f"Error: '{err}'")

def read_query(connection, query):
    cursor = connection.cursor()
    result = None
    try:
        cursor.execute(query)
        result = cursor.fetchall()
        return result
    except Error as err:
        print(f"Error: '{err}'")








from flask import Flask, render_template, request
import mysql.connector
from mysql.connector import Error
app = Flask(__name__)


connection = create_server_connection("127.0.0.1", "tony", "tonton12", "stock_db")





@app.route('/', methods=['GET', 'POST'])
def stock_table():
    if request.method == "POST":
        details = request.form
        firstname= details['fname']
        lastname= details['lname']
        q1="""INSERT INTO fl_test
                        VALUES
                    ('"""+str(firstname)+"""',
                    '"""+str(lastname)+"""');"""

       
        execute_query(connection, q1)
        return 'success'
    else:
        return render_template('index.html')




if __name__ == '__main__':
    app.run()

html code

<!DOCTYPE html>
<html>
<body>
    <h3> Show stock pie graph </h3>
    <form action="{{ url_for('stock_table') }}" method="post">
        Enter First Name:  <input type = "text" name= "fname" />
        Enter Last Name:  <input type = "text" name= "lname" />
            <input type="submit"  value="Go!">
            

            
    </form>

   

</body>
</html>