python3使用alchemy操作mysql完成代码

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import config

#以上导入所需模块
app = Flask(__name__)  #实例化flask
app.config.from_object(config)#引入数据库配置
db = SQLAlchemy(app)   #实例化sqlalchemy
db.create_all()   #测试观察是否有错误

#创建表名
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 index():
    # # 增加数据
    # article1 = Article(title='aaa', content='bbb')
    # db.session.add(article1)
    # # 事务
    # db.session.commit()

    #查找数据
    # article1 = Article.query.filter(Article.title == 'aaa').first()
    # print('title:%s' % article1.title)
    # print('content: %s' % article1.content)

    # #该数据
    # article1 = Article.query.filter(Article.title =='aaa').first()
    # article1.title = 'new title'
    # #事务提交
    # db.session.commit()

    #删除数据
    article1 = Article.query.filter(Article.title == 'new title').first()
    db.session.delete(article1)
    db.session.commit()

    return 'hello'

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


你可能感兴趣的:(python3使用alchemy操作mysql完成代码)