How do I connect to a MySQL Database in Python?

后端 未结 25 1586
眼角桃花
眼角桃花 2020-11-21 07:43

How do I connect to a MySQL database using a python program?

25条回答
  •  一个人的身影
    2020-11-21 08:24

    This is Mysql DB connection

    from flask import Flask, render_template, request
    from flask_mysqldb import MySQL
    
    app = Flask(__name__)
    
    
    app.config['MYSQL_HOST'] = 'localhost'
    app.config['MYSQL_USER'] = 'root'
    app.config['MYSQL_PASSWORD'] = 'root'
    app.config['MYSQL_DB'] = 'MyDB'
    
    mysql = MySQL(app)
    
    
    @app.route('/', methods=['GET', 'POST']) 
    def index():
        if request.method == "POST":
            details = request.form
            cur = mysql.connection.cursor()
            cur.execute ("_Your query_")
            mysql.connection.commit()
            cur.close()
            return 'success'
        return render_template('index.html')
    
    
    if __name__ == '__main__':
        app.run()
    

提交回复
热议问题