Flask连接MySQL数据库
额外说明:MySQL数据库为本地Docker容器
相关库安装:pymysql 和 flask-sqlalchemy
flask连接mysql的步骤
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
app = Flask(__name__)
HOSTNAME="127.0.0.1"
PORT="3306"
USERNAME="root"
PASSWORD='123456'
DATABASE='demo'
#本文驱动为pymysql
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4'
db=SQLAlchemy(app)
#用于测试是否成功连接上数据库,打印出(1,)即成功
with app.app_context():
with db.engine.connect() as conn:
rs = conn.execute(text("select 1"))
print(rs.fetchone())
@app.route('/')
def hello_world():
return 'Hello world!'
if __name__ == '__main__':
app.run(debug=True)