首先创建模型,在数据库里面生成表,然后填入数据,如下
1 # 定义orm,数据模型 2 class Test(db.Model): 3 __tablename__ = ‘test‘ 4 id = db.Column(db.Integer, primary_key=True, autoincrement=True) 5 username = db.Column(db.String(80), unique=True) 6 password = db.Column(db.String(80)) 7 email = db.Column(db.String(120), unique=True) 8 9 def __repr__(self): 10 return ‘<User %r>‘ % self.username 11 12 13 db.create_all() 14 15 @app.route(‘/‘) 16 def index(): 17 # 1.增加 18 admin = Test(username=‘GUEST5‘, password=‘GUEST5‘, email=‘[email protected]‘) 19 db.session.add(admin) # 提交一条数据 20 guestes = [Test(username=‘guest1‘, password=‘guest1‘, email=‘[email protected]‘), 21 Test(username=‘guest2‘, password=‘guest2‘, email=‘[email protected]‘), 22 Test(username=‘guest3‘, password=‘guest3‘, email=‘[email protected]‘), 23 Test(username=‘guest4‘, password=‘guest4‘, email=‘[email protected]‘)] 24 db.session.add_all(guestes) # 提交多条数据 25 db.session.commit() 26 27 return ‘hello world‘ 28 29 30 if __name__ == ‘__main__‘: 31 app.run(debug=True, port=‘6009‘)
0x01:查询用户数目
1 Test.query.count()
0x02:查询所有用户
1 result = Test.query.all()
0x03:查找字段为指定值的用户
1 result = Test.query.filter(Test.username == ‘guest1‘).first()
0x04:查找指定字段以某个字符串开始的用户(根据开头查询)
1 results = Test.query.filter(Test.username.startswith(‘g‘)).all()
0x05:查找指定字段以某个字符串结束的用户(根据结尾查询)
1 results = Test.query.filter(Test.username.endswith(‘1‘)).all()
0x06:查找指定字段包含某个字符串的用户(根据关键字查询)
1 results = Test.query.filter(Test.username.contains(‘e‘)).all()
一位大佬的博文写的很详细,大家可以看一下:https://blog.csdn.net/jlb1024/article/details/81515155
原文地址:https://www.cnblogs.com/liangxiyang/p/11249946.html
时间: 2024-10-08 05:18:15