有人可以在Flask中共享有关如何访问MySQL数据库的示例代码吗?已经有文档显示了如何连接到sqlite,但是没有连接到MySQL。
提前非常感谢你
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@server/db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username
首先,你需要安装Flask-MySQL软件包。使用pip例如:
pip install flask-mysql
接下来,你需要添加一些配置并初始化MySQL:
from flask import Flask from flaskext.mysql import MySQL app = Flask(__name__) mysql = MySQL() app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_PASSWORD'] = 'root' app.config['MYSQL_DATABASE_DB'] = 'EmpData' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app)
现在,你可以获取连接和游标对象并执行原始查询:
conn = mysql.connect() cursor =conn.cursor() cursor.execute("SELECT * from User") data = cursor.fetchone()