在 Flask 中使用 MySQL
有人可以在 Flask 中分享如何访问 MySQL 数据库的示例代码吗?已经有文档显示了如何连接到 sqlite 而不是在 MySQL 上.
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.
在此先非常感谢您
推荐答案
首先你需要安装 Flask-MySQL 包.以 pip
为例:
Firstly you need to install Flask-MySQL package. Using pip
for example:
pip install flask-mysql
接下来需要添加一些配置并初始化MySQL:
Next you need to add some configuration and initialize 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)
现在您可以获取连接和游标对象并执行原始查询:
Now you can get connection and cursor objects and execute raw queries:
conn = mysql.connect()
cursor =conn.cursor()
cursor.execute("SELECT * from User")
data = cursor.fetchone()
相关文章