初始化和设置数据库配置信息
1、使用flask_sqlalchemy中SQLAlchemy进行初始化
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
2、配置数据库config
DIALECT = 'mysql'
DRIVER = 'mysqldb'
USERNAME = 'root'
PASSWORD = 'mysql'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'flask_sql'
SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE)
SQLALCHEMY_TRACK_MODIFICATIONS = False
创建数据库 注:数据库可以提前创建好
create database flask_demo charset utf8;
3、在主app文件中添加配置
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
4、测试数据库是否连接成功 注:运行程序没有报错表示连接成功
db.create_all()
- 5、使用Flask-SQLAlchemy 创建模型与表的映射
class Articles(db.Model):
__tablename__ = 'articles'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
# nullable=False 不能为空
title = db.Column(db.String(32),nullable=False)
content = db.Column(db.Text,nullable=False)
db.drop_all()
- 创建数据库表完整代码
from flask import Flask
import config
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
# nullable=False 不能为空
title = db.Column(db.String(32),nullable=False)
content = db.Column(db.Text,nullable=False)
class Articles(db.Model):
__tablename__ = 'articles'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
# nullable=False 不能为空
title = db.Column(db.String(32),nullable=False)
content = db.Column(db.Text,nullable=False)
db.drop_all()
db.create_all()
@app.route('/')
def index():
return 'Hello World'
if __name__ == '__main__':
app.run(debug=True)