增加数据库中的数据


1、增加单条数据

from flask import Flask
from exts import db
from models import Article

app = Flask(__name__)
app.config.from_pyfile('config.py')
db.init_app(app)

@app.route('/')
def index():
    article = Article(title='文章标题', content='文章内容')
    db.session.add(article)
    db.session.commit()
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

2、增加多条数据

from flask import Flask
from exts import db
from models import Article

app = Flask(__name__)
app.config.from_pyfile('config.py')
db.init_app(app)

@app.route('/')
def index():
    # 方法1
    article1 = Article(title='文章标题1', content='文章内容1')
    article2 = Article(title='文章标题2', content='文章内容2')
    db.session.add(article1)
    db.session.add(article2)
    db.session.commit()
    # 方法2
    # article1 = Article(title='文章标题1', content='文章内容1')
    # article2 = Article(title='文章标题2', content='文章内容2')
    # db.session.add_all([article1,article2])
    # db.session.commit()
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

results matching ""

    No results matching ""