数据库的增改查删
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy import os basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] =\ 'sqlite:///' + os.path.join(basedir, 'data.sqlite') app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True db = SQLAlchemy(app) class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) db.create_all() @app.route('/') def hello_world(): article1 = Article(title = 'aaa', content = 'bbb') db.session.add(article1) db.session.commit() Article.query.all() result = Article.query.filter(Article.title == 'aaa').all() article1.title = 'new title' db.session.commit() result = Article.query.filter(Article.content == 'bbb').first() db.session.delete(result) return 'Hello World!' if __name__ == '__main__': app.run()
|