本文共 1874 字,大约阅读时间需要 6 分钟。
pip3 install flask-sqlalchemypip3 install pymysql
vs ide保存时报错,忽略试试是否可执行
app = Flask(__name__)app.config['SECRET_KEY'] = 'haha'app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://wiki_w:123456@10.16.17.99:3499/flaskr'app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True #设置这一项是每次请求结束后都会自动提交数据库中的变动db = SQLAlchemy(app) #实例化class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(320), unique=True) phone = db.Column(db.String(32), nullable=False) def __init__(self, username, email, phone): self.username = username self.email = email self.phone= phoneif __name__ == '__main__': db.drop_all() db.create_all()
## 插入...........inset=User(username='itmin', email='itmin@qq.com', phone='13812345678')db.session.add(inset)db.session.commit()## 更新..............news=User.query.all()print newsnews[1].username='test'db.session.commit()## 删除name=User.query.filter_by(username = 'bb').first()db.session.delete(name)db.session.commit()## 查询1、精确匹配select_=User.query.filter_by(username='itmin').first()print(select_.id)2、模糊匹配query = User.query.filter(User.email.endswith('@qq.com')).all()print(query)3、反向查询query = User.query.filter(User.username != 'yoyo').first()print(query)4、或查询query = User.query.filter(or_(User.username != 'yoyo', User.email.endswith('@example.com'))).first()print(query)5、与查询query = User.query.filter(and_(User.username != 'yoyo', User.email.endswith('@example.com'))).first()print(query)6、查询返回数据的数目num = User.query.limit(10).all()print(num)7、查询全部data_all = User.query.all()print(data_all) for i in range(len(data_all)): print(data_all[i].username+" "+data_all[i].email+" "+data_all[i].phone)
转载于:https://blog.51cto.com/tengxiansheng/2108273