SQLAlchemy查詢數據庫數據


首先創建模型,在數據庫里面生成表,然后填入數據,如下

 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='GUEST5@example.com')
19     db.session.add(admin)  # 提交一條數據
20     guestes = [Test(username='guest1', password='guest1', email='guest1@example.com'),
21                Test(username='guest2', password='guest2', email='guest2@example.com'),
22                Test(username='guest3', password='guest3', email='guest3@example.com'),
23                Test(username='guest4', password='guest4', email='guest4@example.com')]
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM