Flask项目中,使用使用flask_sqlalchemy连接MySQL数据库并在数据库中创建数据表
问题描述
- 在app.py中写完以下一大段代码后,直接点击Pycharm的绿色按钮运行项目(如图),发现数据库中一直没有能成功在数据库中创建数据表
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/412cb59924edcaced5bf4b43b670734f.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ba960d1a4d5404c62ee9c493e7690474.png)
解决方案:
- 代码编写完成后不能直接点击Pycharm的绿色按钮运行项目
- 将
app.run(host='0.0.0.0', port=8080, debug=True)
这一段代码注释掉后,在Terminal命令行中输入python app.py来运行(如图)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2f88997e37d93d1d587a08b02627e381.png)
代码
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://MySQL用户名:MySQL密码@127.0.0.1:3306/数据库名称'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
@app.route('/')
def hello_world():
return 'Hello World!'
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(16), unique=True)
class User(db.Model):
__tablename__ = 'users'
user_id = db.Column(db.Integer, primary_key=True)
user_name = db.Column(db.String(16), unique=True)
roles_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
if __name__ == '__main__':
db.drop_all()
db.create_all()