flask mysql config
时间: 2023-07-05 21:31:21 浏览: 40
To configure Flask to work with MySQL, you first need to install the necessary packages. You can do this using pip by running the following command:
```
pip install flask-mysql
```
Once you have installed the package, you can then create a connection to your MySQL database using the following code:
```python
from flask import Flask
from flaskext.mysql import MySQL
app = Flask(__name__)
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'your_username'
app.config['MYSQL_DATABASE_PASSWORD'] = 'your_password'
app.config['MYSQL_DATABASE_DB'] = 'your_database'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
```
In this code, you should replace `your_username`, `your_password`, and `your_database` with your own MySQL database credentials. You can then use the `mysql` object to execute SQL queries on your database.
For example:
```python
@app.route('/')
def index():
cursor = mysql.get_db().cursor()
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
return str(users)
```
This will execute a simple SQL query to select all the rows from the `users` table and return the result as a string.