TinyDB - 处理数据查询
TinyDB - 存储多个数据
我们已经讨论了如何使用"insert"查询将数据存储在数据库中。 同样,您可以使用"insert_multiple"查询同时存储多个数据项。 这是 TinyDB 中"insert_multiple"查询的语法:
db.insert_multiple ([ { key1 : value1, key2 : value2, ..., keyN : valueN}, { key1 : value1, key2 : value2, ..., keyN : valueN } ])
让我们举几个例子来演示"insert_multiple"查询的工作原理。 我们将使用与前面所有章节中使用的相同的student数据库。
示例 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" } ]
可以看到学生的两条新记录已保存到数据库中。
示例 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 循环来插入三个新条目。