English 中文(简体)
TinyDB - Tables
  • 时间:2024-09-17

TinyDB - Tables


Previous Page Next Page  

In TinyDB, we can work with multiple tables. These tables have the same properties as the TinyDB class. Let s see how we can create tables in TinyDB and apply various operations on them −

Creating Tables

It’s very easy to create a table in TinyDB. Here s its syntax −


table_object = db.table( table name )

Inserting Values in a Table

To insert data in a specific table, use the following syntax −


table_object.insert({  key  : value })

Retreiving Values from a Table

To retrieve values from a table, use the following query −


table_object.all()

Deleting a Table from a Database

To delete a table from a database, use the drop_table() query. Here is its syntax


db.drop_table( table name )

Delete Multiple Tables from a Database

To delete multiple tables from a database, use the following query −


db.drop_tables()

Let s understand how to use these queries with the help of a few examples. We will use the same student database that we have used in all the previous chapters.

Example 1

Use the following code to create a new table called Student_Detail


from tinydb import TinyDB, Query
db = TinyDB("student.json")
table_object = db.table( Student_Detail )

Example 2

Next, let s insert values in this new table Student_Detail


from tinydb import TinyDB, Query
db = TinyDB("student.json")
table_object = db.table( Student_Detail )
table_object.insert({
    roll_number : 1,
    st_name :  elen ,
    mark : 250,
    subject :  TinyDB ,
    address :  delhi 
})

It will return the doc_id of the record inserted in the table.


[1]

To verify, use the following code −


from tinydb import TinyDB, Query
db = TinyDB("student.json")
table_object = db.table( Student_Detail )
table_object.all()

It will show data contained in the Student_Detail table −


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

Example 3

To see all the tables present in the database, use the following query −


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

There are two tables inside "student.json". It will show the names of these two tables −


{ Student_Detail ,  _default }

Example 4

Let s see how we can reterive all the values from a table −


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

It will show the following output


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

Example 5

Let s see how we can remove a table from a database −


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

It will remove the "Student_Detail" table from the database. To remove all the tables from a database, use the "drop_tables()" query −


db.drop_tables()

It will remove all the tables from the database.

Advertisements