Google News
logo
TinyDB - Interview Questions
How do you create a new TinyDB database?
Creating a new TinyDB database is a straightforward process. Here's how you can do it in Python:

Install TinyDB : If you haven't already installed TinyDB, you can do so using pip:
pip install tinydb?

Import TinyDB : Import the TinyDB library in your Python script or interactive session:
from tinydb import TinyDB?

Create a new database instance : Use the TinyDB class constructor to create a new instance of the database. You can optionally specify the storage backend as an argument. If no storage backend is provided, TinyDB defaults to in-memory storage:
# Create a new TinyDB instance with default in-memory storage
db = TinyDB()

# Alternatively, specify a JSON file as the storage backend
# db = TinyDB('db.json')?

This creates a new instance of the TinyDB database. If you provide a filename (e.g., 'db.json'), TinyDB will use that file for persistent storage. If you don't provide a filename, TinyDB will use in-memory storage, which is useful for temporary data or testing purposes.

Start using the database : Now that you've created the database instance, you can start inserting, querying, updating, and deleting data in the database using TinyDB's API.
Here's a simple example of inserting data into the database:
# Insert a document into the database
db.insert({'name': 'Alice', 'age': 30})

# Insert another document
db.insert({'name': 'Bob', 'age': 25})?

And here's how you can query data from the database:
# Query all documents in the database
all_documents = db.all()
print(all_documents)

# Query documents that match certain criteria
query_result = db.search(Query().age == 25)
print(query_result)?

This is how you can create a new TinyDB database and start using it to store and retrieve data in your Python applications.
Advertisement