Write A Simple Toy Database in Python within Minutes!
Tags: python, database, beginners, tutorial
Published: 2019-01-31 09:42:07

---
title: Write A Simple Toy Database in Python within Minutes!
published: true
description: 
tags: python , database , beginners, tutorial
cover_image: https://thepracticaldev.s3.amazonaws.com/i/lkk6uuu4rfktgpwv9w09.jpg
canonical_url: https://dev.palashbauri.in/write-a-simple-toy-database-in-python-within-minutes-ck5th6dc907m9qks1lnll0ujz
---

MySQL, PostgreSQL, Oracle, Redis... and many more you just name it... Databases are really an important piece of technology in the progress of human civilization. Today we can see how valuable **Data** is and so as keeping them safe and stable, this is where the database comes!

We can see how important databases are. For a quite some time I was thinking of creating My Own Toy Database just to understand, play and experiment with it as **Richard Feynman** said

> <h3 align="center">What I cannot create, I do not understand</h3>

So Without any further talking let's jump into the fun part... Coding... 

For this Toy Database, We'll use **Python** (My Favourite :heart:), I named this database **FooBarDB** (I couldn't find any name ;)), but you can call it whatever you want!

So first let's import some necessary python libraries which are already available in Python Standard Library

```python
import json
import os
```
Yes, We only need this two libs! `json` as our database will be based on json and `os` for some path related stuff!

Now Let's define the main class `FoobarDB` with some pretty basic function which I'll explain them below.

```python
class FoobarDB(object):
    def __init__(self , location):
        self.location = os.path.expanduser(location)
        self.load(self.location)
            
    def load(self , location):
        if os.path.exists(location):
            self._load()
        else:
            self.db = {}
        return True
 
    def _load(self):
        self.db = json.load(open(self.location , "r"))
        
    def dumpdb(self):
        try:
            json.dump(self.db , open(self.location, "w+"))
            return True
        except:
            return False

```
Here we defined our main class with a `__init__` function, whenever creating a Foobar Database we only need to pass the location of the database. 
In the first `__init__` function we take the location parameter and replace `~` or `~user` with users home directory to make it work intended way, and finally put it in `self.location` variable to access it later on the same class functions. At the end, we are calling the `load` function passing `self.location` as an argument.


```python
. . . .
    def load(self , location):
        if os.path.exists(location):
            self._load()
        else:
            self.db = {}
        return True
. . . .
        
```
In the next `load` function we take the location of the database as param, then check if the database exists or not, if it exists, we simply load it with `_load()` function (explained below) otherwise we create an empty in-memory JSON object. And Finally, return true on success.

```python
. . . . 

    def _load(self):
        self.db = json.load(open(self.location , "r"))
. . . . 

```

In `_load` function we just simply open the database file from the location stored in `self.location` then transform it into JSON object and loads it into `self.db` variable.

```python
. . . .
    def dumpdb(self):
        try:
            json.dump(self.db , open(self.location, "w+"))
            return True
        except:
            return False
            
. . . .
```

And Finally the `dumpdb` function, its name says what it does, it basically just take the in-memory database (actually a JSON object) from `self.db` variable and saves it in the database file! It returns **True** if saved successfully otherwise returns **False**

But, Wait a Minute! 😐 A Database is useless if it can't store and retrieve data, isn't it? 😉 Let's Go and add them also...😎

```python
. . . .
    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 them save the database, if everything goes right it will return True other it will print an error message and return False (We don't want it to crash and erase our data everytime an error occurs 😎).

```python
. . . .
    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 database other False is returned with a message.

```python
. . . .
    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 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 returns false.

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

```python
. . . . 
    
    def resetdb(self):
        self.db={}
        self.dumpdb()
        return True
. . . .
```
Here's the function to reset the database, `resetdb`! It's so simple, First we do is re-assign our in-memory database with an empty JSON  object and just saves it! And that's it! Our Database is now again clean shaved! 

Full Source is Here 👉 [bauripalash/foobardb](https://github.com/bauripalash/foobardb)

---
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! 

I hope, You Enjoyed! Let Me Know Your Suggestions, Ideas or Mistakes I've made in the comments below! 👇

Follow/Ping Me On Socials 👉 [Facebook](https://facebook.com/bauripalash) , [Twitter](https://twitter.com/bauripalash) , [Instagram](https://instagram.com/bauripalash)

Thank You! See You Soon!

---
If You Like My Work (My Articles, Stories, Softwares, Researches and many more) Consider [Buying Me A Coffee ☕](https://www.buymeacoffee.com/palash) 🤗