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
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 %}