TinyDB - 检索数据



有多种方法可以帮助您从 TinyDB 数据库中检索数据。但要使用这些方法,您首先需要创建一个 Query 类的实例,如下所示:

from tinydb import Query
Student = Query()

这里,Student 是数据库的名称。

让我们检查从 TinyDB 数据库检索信息的不同方法。

使用 search() 方法检索数据

search() 方法顾名思义,返回与我们提供的查询匹配的项目列表,否则将返回空列表。

对于此示例和其他示例,我们将使用以下student 数据库数据:

[
   {
      "roll_number": 1,
      "st_name": "elen",
      "mark": 250,
      "subject": "TinyDB",
      "address": "delhi"
   },
   {
      "roll_number": 2,
      "st_name": "Ram",
      "mark": [
         250,
         280
      ],
      "subject": [
         "TinyDB",
         "MySQL"
      ],
      "address": "delhi"
   },
   {
      "roll_number": 3,
      "st_name": "kevin",
      "mark": [
         180,
         200
      ],
      "subject": [
         "oracle",
         "sql"
      ],
      "address": "keral"
   },
   {
      "roll_number": 4,
      "st_name": "lakan",
      "mark": 200,
      "subject": "MySQL",
      "address": "mumbai"
   },
   {
      "roll_number": 5,
      "st_name": "karan",
      "mark": 275,
      "subject": "TinyDB",
      "address": "benglore"
   }
]

让我们以一个示例来理解 search() 方法:

from tinydb import TinyDB, Query
db = TinyDB("leekha.json")
student = Query()
db.search(student.subject == 'TinyDB' )

上述查询将从 student 数据库检索以下输出

[
   {
      "roll_number":1,
      "st_name":"elen",
      "mark":250,
      "subject":"TinyDB",
      "address":"delhi"
   },
   {
      "roll_number":5,
      "st_name":"karan",
      "mark":275,
      "subject":"TinyDB",
      "address":"benglore"
   }
]

使用 get() 方法检索数据

与 search() 方法相反,get() 方法只返回一个匹配的文档。否则将返回 None。例如,让我们看以下代码:

from tinydb import TinyDB, Query
student = Query()
db.get(student.subject == 'TinyDB' )

上述查询将从student 数据库检索以下数据。

[{'roll_number': 1, 'st_name': 'elen', 'mark': 250, 'subject': 'TinyDB', 'address': 'delhi'}]

使用 all() 方法检索数据

all() 方法返回数据库中的所有文档。例如,

db.all()

它将从 student 数据库检索所有数据。

[
   {
      "roll_number":1,
      "st_name":"elen",
      "mark":250,
      "subject":"TinyDB",
      "address":"delhi"
   },
   {
      "roll_number":2,
      "st_name":"Ram",
      "mark":[
         250,
         280
      ],
      "subject":[
         "TinyDB",
         "MySQL"
      ],
      "address":"delhi"
   },
   {
      "roll_number":3,
      "st_name":"kevin",
      "mark":[
         180,
         200
      ],
      "subject":[
         "oracle",
         "sql"
      ],
      "address":"keral"
   },
   {
      "roll_number":4,
      "st_name":"lakan",
      "mark":200,
      "subject":"MySQL",
      "address":"mumbai"
   },
   {
      "roll_number":5,
      "st_name":"karan",
      "mark":275,
      "subject":"TinyDB",
      "address":"benglore"
   }
]

使用 for 循环检索数据

for 循环也返回数据库中的所有文档。例如,

for info in db:
   print(info)

就像 all() 方法一样,它将从 student 数据库检索所有行。

广告