Tinydb 简明教程

TinyDB - Default Table

TinyDB 提供了一个默认表,用于自动保存和修改数据。我们还可以将一个表设置为默认表。基本查询、方法和操作将针对该默认表执行。在本章中,让我们看看如何查看数据库中的表以及如何将我们选择的一个表设置为默认表:

TinyDB provides a default table in which it automatically saves and modifies the data. We can also set a table as the default table. The basic queries, methods, and operations will work on that default table. In this chapter, let’s see how we can see the tables in a database and how we can set a table of our choice as the default table −

Showing the Tables in a Database

要获取数据库中所有表的列表,请使用以下代码:

To get the list of all the tables in a database, use the following code −

from tinydb import TinyDB, Query
db = TinyDB("student.json")
db.tables()

它将产生以下内容 output :我们有两个表位于 "student.json" 中,因此它将显示这两个表的名称:

It will produce the following output: We have two tables inside "student.json", hence it will show the names of these two tables −

{'Student_Detail', '_default'}

输出显示,我们的数据库中有两个表,一个是 "Student_Detail",另一个是 "_default"。

The output shows that we have two tables in our database, one is "Student_Detail" and the other "_default".

Displaying the Values of the Default Table

如果您使用 all() 查询,它将显示默认表的表述:

If you use the all() query, it will show the contents of the default table −

from tinydb import TinyDB
db = TinyDB("student.json")
db.all()

要显示 "Student_Detail" 表的表述,请使用以下查询:

To show the contents of the "Student_Detail" table, use the following query −

from tinydb import TinyDB
db = TinyDB("student.json")
print(db.table("Student_Detail").all())

它将显示 "Student_Detail" 表的表述:

It will show the contents of the "Student_Detail" table −

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

Setting a Default Table

您可以将您选择的表设置为默认表。为此,您需要使用以下代码:

You can set a table of your choice as the default table. For that, you need to use the following code −

from tinydb import TinyDB
db = TinyDB("student.json")
db.default_table_name = "Student_Detail"

它将把 "Student_Detail" 表设置为我们数据库的默认表。

It will set the "Student_Detail" table as the default table for our database.