【问题标题】:Unable to run Mysql Insert command using Flask app无法使用 Flask 应用程序运行 Mysql Insert 命令
【发布时间】:2021-05-15 06:03:05
【问题描述】:

我有一个烧瓶应用程序,需要将数据插入到 mysql 的 db 表中,所以无论我给它什么端口或主机都会向我抛出如下错误。

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)

这是我的代码:

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)

由于已经创建了 DB 和 Table,我将这些行注释掉了。它目前部署在 Windows 远程服务器中,并且在连接到控制台之前打印。我不知道是不是这个原因。谁能帮我弄清楚为什么会这样

【问题讨论】:

    标签: python mysql flask


    【解决方案1】:

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

    上面的链接帮助我找到了您正在寻找的答案。

    我必须做一些小的调整以使其适合我制作的 mysql 函数。

    我在我的代码下方发布。

    python 代码

    ##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代码

    <!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>
    

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 2020-04-26
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多