flask-mysql和sqlalchemy
时间: 2023-12-31 15:23:13 浏览: 114
flask-mysql是一个Flask扩展,它提供了一种使用MySQL数据库的简单方法。它允许您轻松地连接到MySQL数据库并执行查询。以下是使用flask-mysql连接MySQL数据库的步骤:
1.安装flask-mysql扩展
```shell
pip install flask-mysql
```
2.在Flask应用程序中配置MySQL数据库连接
```python
from flask import Flask
from flaskext.mysql import MySQL
app = Flask(__name__)
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'password'
app.config['MYSQL_DATABASE_DB'] = 'mydb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
```
3.在Flask应用程序中执行MySQL查询
```python
from flask import Flask
from flaskext.mysql import MySQL
app = Flask(__name__)
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'password'
app.config['MYSQL_DATABASE_DB'] = 'mydb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
@app.route('/')
def index():
cursor = mysql.get_db().cursor()
cursor.execute('SELECT * FROM mytable')
data = cursor.fetchall()
return str(data)
```
SQLAlchemy是一个Python SQL工具包和ORM,它提供了一种使用SQL数据库的简单方法。它允许您轻松地连接到SQL数据库并执行查询。以下是使用SQLAlchemy连接MySQL数据库的步骤:
1.安装SQLAlchemy
```shell
pip install sqlalchemy
```
2.在Python应用程序中配置MySQL数据库连接
```python
from sqlalchemy import create_engine
# MySQL configurations
user = 'root'
password = 'password'
host = 'localhost'
database = 'mydb'
engine = create_engine(f'mysql://{user}:{password}@{host}/{database}')
```
3.在Python应用程序中执行MySQL查询
```python
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
# MySQL configurations
user = 'root'
password = 'password'
host = 'localhost'
database = 'mydb'
engine = create_engine(f'mysql://{user}:{password}@{host}/{database}')
metadata = MetaData()
mytable = Table('mytable', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
Column('age', Integer),
)
with engine.connect() as conn:
result = conn.execute(mytable.select())
for row in result:
print(row)
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)