Tinydb 简明教程
TinyDB - Handling Data Query
TinyDB - Storing Multiple Data
我们已经讨论了如何使用 ' insert ' 查询将数据存储在数据库中。类似地,可以使用 ' insert_multiple ' 查询同时存储多个数据项。以下是在 TinyDB 中 ' insert_multiple ' 查询的语法:
db.insert_multiple ([
{ key1 : value1, key2 : value2, ..., keyN : valueN},
{ key1 : value1, key2 : value2, ..., keyN : valueN }
])
我们来看几个示例,以演示“insert_multiple”查询的工作原理。我们将使用在之前的章节中使用的相同的 student 数据库。
Example 1
让我们看看如何使用 insert_multiple 查询在我们 ' student ' 表中插入两条学生记录 −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.insert_multiple([
{
"roll_number":6,
"st_name":"Siya",
"mark":240,
"subject":"NoSQL",
"address":"pune"
},
{
"roll_number":7,
"st_name":"Adam",
"mark":210,
"subject":"oracle",
"address":"Keral"
}
])
它将显示新保存记录的文档 ID −
[6, 7]
让我们检查一下新记录是否已保存到数据库中?使用 all() 方法,如下所示 −
db.all()
它将显示存储在给定表中的所有记录 −
[
{
"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"
},
{
"roll_number":6,
"st_name":"Siya",
"mark":240,
"subject":"NoSQL",
"address":"pune"
},
{
"roll_number":7,
"st_name":"Adam",
"mark":210,
"subject":"oracle",
"address":"Keral"
}
]
你可以看到 students 的两条新记录已保存到数据库中。
Example 2
让我们看看如何使用 insert_multiple 和 for 循环一次性在表中插入多个值。使用以下代码 −
db.insert_multiple({'roll_number': 10, 'numbers': r} for r in range(3))
它将返回新保存记录的文档 ID −
[8, 9, 10]
再次使用 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"
},
{
"roll_number":6,
"st_name":"Siya",
"mark":240,
"subject":"NoSQL",
"address":"pune"
},
{
"roll_number":7,
"st_name":"Adam",
"mark":210,
"subject":"oracle",
"address":"Keral"
},
{
"roll_number":10,
"numbers":0
},
{
"roll_number":10,
"numbers":1
},
{
"roll_number":10,
"numbers":2
}
]
请注意最后三行。我们已将 insert_multiple 方法与 for 循环配合使用,以插入三个新条目。