flask3:Mysql数据库操作(Database First)
程序员文章站
2023-12-28 11:56:46
...
1.安装插件
pipenv install flask-sqlalchemy
Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning.
Installing flask-sqlalchemy…
✔ Installation Succeeded
Installing dependencies from Pipfile.lock (5ea30a)…
???? ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 8/8 — 00:00:05
2.安装驱动
pipenv install pymysql
Installing pymysql…
✔ Installation Succeeded
Installing dependencies from Pipfile.lock (b0a7e7)…
???? ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 9/9 — 00:00:04
3.配置文件中增加配置项
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]/admin'
4. 代码
from flask import Flask
from test.db.models import User, db
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/admin?charset=utf8'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
#将应用上下文推入栈,否则无法运行
ctx = app.app_context()
ctx.push()
db.init_app(app)
user = User.query.filter_by(account = 'ljz').first()
if user:
print(user.name)
else:
print('not found')
推荐阅读
-
flask3:Mysql数据库操作(Database First)
-
cmd 操作mysql数据库相关问题
-
六条比较有用的MySQL数据库操作的SQL语句小结
-
MySQL之终端Terminal(dos界面)管理数据库、数据表、数据的基本操作_MySQL
-
PowerDesigner修改MySQL数据库的Table或DataBase的ENGINE(存储引擎)类型_MySQL
-
使用SQL操作MySQL数据库
-
简单的php操作mysql数据库实现_PHP教程
-
MySQL数据库所支持的操作系统_MySQL
-
php简单操作mysql数据库的类_PHP
-
深入探讨:PHP使用数据库永久连接方式操作MySQL的是与非