用flask框架连接mysql代码
时间: 2023-11-18 20:52:11 浏览: 72
flask 框架操作MySQL数据库简单示例
以下是使用Flask框架连接MySQL数据库的代码示例:
```python
from flask import Flask
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'your-username'
app.config['MYSQL_PASSWORD'] = 'your-password'
app.config['MYSQL_DB'] = 'your-database'
mysql = MySQL(app)
@app.route('/')
def users():
cur = mysql.connection.cursor()
result = cur.execute("SELECT * FROM users")
users = cur.fetchall()
cur.close()
return str(users)
if __name__ == '__main__':
app.run()
```
您可以根据您的实际情况修改`MYSQL_HOST`,`MYSQL_USER`,`MYSQL_PASSWORD`和`MYSQL_DB`来连接到您的MySQL数据库。在路由函数中,我们使用`mysql.connection.cursor()`来获取游标,执行SQL查询,并使用`cur.fetchall()`来获取结果。最后,我们使用`cur.close()`关闭数据库连接。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [flask 框架如何连接 mysql](https://blog.csdn.net/weixin_35754676/article/details/128870503)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *3* [python连接MySQL数据库最简单方式-----Flask框架连接mysql数据库](https://blog.csdn.net/qq_42489668/article/details/124048087)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文