Tinydb 简明教程
TinyDB - Delete Data
如果您需要从 TinyDB 数据库中永久删除特定数据的话,您可以使用 remove() 方法来完成。与返回和更新数据类似,您首先需要创建一个 Query 类的实例来删除数据。您可以为此目的使用以下命令 -
from tinydb import Query
Student = Query()
这里 Student 是我们数据库的名称。
The remove() Method
以下是 remove() 方法的语法 -
db.remove( Query() field regex )
remove() 方法接受可选条件以及可选文档 ID 列表。
The student Database
对于本章的示例,我们将使用以下 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"
}
]
Example: Deleting a Single Row of Data
我们举一个例子来了解 remove() 方法。
from tinydb import TinyDB, Query
student = Query()
db.remove(student.roll_number == 5)
上面的查询将删除学生学号为 5 的数据。它将返回被删除对象的 ID −
[5]
现在,我们可以使用 all() 方法查看更新后的数据库。
db.all()
它将显示更新后数据库中的数据 −
[
{
"roll_number":1,
"st_name":"Adam",
"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"
}
]
Example: Deleting Multiple Rows of Data
如果您一次想要删除多行,您可以按如下所示使用 remove() 方法 −
from tinydb import TinyDB, Query
student = Query()
db.remove(student.roll_number > 2)
它将返回被删除对象的 ID:
[3,4]
使用 all() 方法查看更新后的数据库。
db.all()
它将显示更新后数据库中的数据 −
[
{
"roll_number":1,
"st_name":"Adam",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
}
]