创建数据库表的基本指令:
db.drop_all()
db.create_all()
完整代码如下:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
class Config(object):
"""配置参数"""
SQLALCHEMY_DATABASE_URI = "mysql://root:123456@127.0.0.1:3306/db_python"
SQLALCHEMY_TRACK_MODIFICATIONS = True
app.config.from_object(Config)
db = SQLAlchemy(app)
class Role(db.Model):
"""用户角色/身份表"""
__tablename__ = "tbl_roles"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32), unique=True)
users = db.relationship("User", backref="role")
class User(db.Model):
"""用户表"""
__tablename__ = "tbl_users"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
email = db.Column(db.String(128), unique=True)
passward = db.Column(db.String(128))
role_id = db.Column(db.Integer, db.ForeignKey("tbl_roles.id"))
@app.route("/")
def start():
return "This is the beginning"
if __name__ == '__main__':
db.drop_all()
db.create_all()
role1 = Role(name="admin")
db.session.add(role1)
db.session.commit()
role2 = Role(name="stuff")
db.session.add(role2)
db.session.commit()
user_1 = User(name="zhangsan", email="123@123.com", passward="123", role_id=role1.id)
user_2 = User(name="lisi", email="234@234.com", passward="234", role_id=role1.id)
user_3 = User(name="wangwu", email="345@345.com", passward="345", role_id=role2.id)
user_4 = User(name="zhaoliu", email="456@456.com", passward="456", role_id=role2.id)
db.session.add_all([user_1, user_2, user_3, user_4])
db.session.commit()
查看创建好的数据库表可先打开cmd窗口,输入以下命令”
"""
查看创建好的数据库指令:
net start mysql 启动MySQL
mysql -u root -p 进入MySQL
Enter password: 123456 输入MySQL命令
mysql> show databases; 显示数据库
mysql> use db_python; 连接数据库
mysql> show tables; 显示数据库表
mysql> desc tbl_roles; 显示tbl_roles表参数
mysql> desc tbl_users; 显示tbl_users表参数
mysql> select * from tbl_roles; 查询所有tbl_roles行
mysql> select * from tbl_users; 查询所有tbl_users行
"""
最终效果如下: 以上就是Flask创建数据库表的基本方法,各位读者有疑问的可以私信博主或评论留下足迹。
|