通过用户模型,对数据库进行增删改查操作。
增加:
user =
db.session.add(user)
db.session.commit()
查询:
User.query.filter(User.username == 'mis1114').first()
修改:
user.password = '111111'
db.session.commit()
删除:
db.session.delete(user)
db.session.commit()
from flask import Flask from flask_sqlalchemy import SQLAlchemy import config app = Flask(__name__) app.config.from_object(config) db=SQLAlchemy(app) class User(db.Model): __tablename__ = 'User' id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(20),nullable=False) password = db.Column(db.String(20),nullable=False) nickname = db.Column(db.String(20)) #db.create_all() #增 user=User(username='liu1234',password='123456789') db.session.add(user) db.session.commit() #删 user=User.query.filter(User.username=='two1234').first() user.password='12345678910' db.session.delete(user) db.session.commit() #改 user=User.query.filter(User.username=='two1234').first() user.username='three1234' db.session.add(user) db.session.commit() #查 user=User.query.filter(User.username=='two1234').first() print(user.id,user.username,user.password) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()
SQLALCHEMY_DATABASE_URI='mysql+pymysql://root:@127.0.0.1:3306/mis_db?charset=utf8' SQLALCHEMY_TRACK_MODIFICATIONS = False