Using MySQL in Flask

前端 未结 8 792
忘掉有多难
忘掉有多难 2020-12-02 11:46

Can someone share example codes in Flask on how to access a MySQL DB? There have been documents showing how to connect to sqlite but not on MySQL.

Thank you very muc

8条回答
  •  眼角桃花
    2020-12-02 12:05

    Pretty simple with pymysql:

    from flask import Flask, request, render_template
    import pymysql
    
    db = pymysql.connect("localhost", "username", "password", "database")
    
    app = Flask(__name__)
    api = Api(app)
    
    @app.route('/')
    def someName():
        cursor = db.cursor()
        sql = "SELECT * FROM table"
        cursor.execute(sql)
        results = cursor.fetchall()
        return render_template('index.html', results=results)
    
    if __name__ == '__main__':
    app.run(debug=True)
    

    In your index.html file just do something like:

    <% for row in results %} {{ row[0] }} {{ row[1] }} {{ row[2] }} {{ row[3] }} {% endfor %}

提交回复
热议问题