flask连接mysql数据库
时间: 2023-10-09 18:12:29 浏览: 110
flask-MySql
1. 安装mysql-connector-python包:
```
pip install mysql-connector-python
```
2. 在Flask中配置MySQL连接:
```python
from flask import Flask
import mysql.connector
app = Flask(__name__)
# 配置MySQL连接
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'database'
# 创建MySQL连接
conn = mysql.connector.connect(
host=app.config['MYSQL_HOST'],
user=app.config['MYSQL_USER'],
password=app.config['MYSQL_PASSWORD'],
database=app.config['MYSQL_DB']
)
# 创建游标对象
cursor = conn.cursor()
@app.route('/')
def index():
# 使用游标查询数据
cursor.execute('SELECT * FROM table')
result = cursor.fetchall()
return result
if __name__ == '__main__':
app.run()
```
3. 在Flask中使用ORM库(例如SQLAlchemy)连接MySQL:
```python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# 配置MySQL连接
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost/database'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 创建SQLAlchemy对象
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
age = db.Column(db.Integer)
@app.route('/')
def index():
# 查询数据
users = User.query.all()
return users
if __name__ == '__main__':
app.run()
```
阅读全文