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

TinyDB - Default Table


Previous Page Next Page  

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 pst of all the tables in a database, use the following code −


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

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 }

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

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()

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())

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"

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

Advertisements