Google News
logo
TinyDB - Interview Questions
How do you insert data into a TinyDB database?
In TinyDB, you can insert data into the database by adding documents to a table. Here's how you can insert data into a TinyDB database:

Get a reference to the table : If you haven't already created the table, you can do so by calling the table() method on the TinyDB instance. This method creates a new table if it doesn't exist or returns a reference to an existing table.

Insert data into the table : Once you have a reference to the table, you can insert data into it using the insert() method. This method takes a dictionary representing the document to be inserted as its argument.

Here's a step-by-step example :
from tinydb import TinyDB

# Create a new TinyDB instance with JSON file storage
db = TinyDB('db.json')

# Get a reference to the 'users' table (create it if it doesn't exist)
users_table = db.table('users')

# Define a new document to insert into the table
new_user = {'name': 'Alice', 'age': 30}

# Insert the new document into the 'users' table
users_table.insert(new_user)

# Optionally, you can insert multiple documents at once using the 'insert_multiple()' method
additional_users = [
    {'name': 'Bob', 'age': 25},
    {'name': 'Charlie', 'age': 35}
]
users_table.insert_multiple(additional_users)?

In this example :

* We create a new TinyDB instance with JSON file storage.
* We obtain a reference to the 'users' table using the table() method. If the table doesn't exist, it will be created.
* We define a new document new_user as a dictionary with keys 'name' and 'age'.
* We insert the new_user document into the 'users' table using the insert() method.
* Additionally, we insert multiple documents at once using the insert_multiple() method, passing in a list of dictionaries representing the documents to be inserted.

After running this code, the data will be inserted into the 'users' table in the TinyDB database, ready for further querying and manipulation.
Advertisement