How to write a simple toy database in Python within minutes

Let’s go and add them also…????.

.

.

.

def set(self , key , value): try: self.

db[str(key)] = value self.

dumpdb() return True except Exception as e: print("[X] Error Saving Values to Database : " + str(e)) return False def get(self , key): try: return self.

db[key] except KeyError: print("No Value Can Be Found for " + str(key)) return False def delete(self , key): if not key in self.

db: return False del self.

db[key] self.

dumpdb() return True.

.

.

.

The set function is to add data to the database.

As our database is a simple key-value based database, we’ll only take a key and value as an argument.

First, we’ll try to add the key and value to the database and then save the database.

If everything goes right it will return True.

Otherwise, it will print an error message and return False.

(We don’t want it to crash and erase our data every time an error occurs ????).

.

.

.

def get(self, key): try: return self.

db[key] except KeyError: return False.

.

.

.

get is a simple function, we take key as an argument and try to return the value linked to the key from the database.

Otherwise False is returned with a message.

.

.

.

def delete(self , key): if not key in self.

db: return False del self.

db[key] self.

dumpdb() return True.

.

.

.

delete function is to delete a key as well as its value from the database.

First, we make sure the key is present in the database.

If not we return False.

Otherwise, we delete the key with the built-in del which automatically deletes the value of the key.

Next, we save the database and it returns false.

Now you might think, what if I’ve created a large database and want to reset it?.In theory, we can use delete — but it's not practical, and it’s also very time-consuming!.⏳ So we can create a function to do this task.

.

.

.

def resetdb(self): self.

db={} self.

dumpdb() return True.

.

.

.

Here’s the function to reset the database, resetdb!.It's so simple: first, what we do is re-assign our in-memory database with an empty JSON object and it just saves it!.And that's it!.Our Database is now again clean shaven.

Finally… ????That’s it friends!.We have created our own Toy Database !.????????.Actually, FoobarDB is just a simple demo of a database.

It’s like a cheap DIY toy: you can improve it any way you want.

You can also add many other functions according to your needs.

Full Source is Here ????.bauripalash/foobardbI hope, you enjoyed it!.Let me know your suggestions, ideas or mistakes I’ve made in the comments below!.????Follow/ping me on socials ????. More details

Leave a Reply