Building a simple relational database from scratch involves implementing some of key concepts we've discussed in the previous sections. For our example, we will use Python to build a simple in-memory relational database that supports basic operations like writing, reading and updating data.
First, let's start by creating a Dictionary that will serve as our database. In Python, Dictionaries are a data structure similar to hash tables where every entry is a key-value pair. Thus, they are a perfect option to implement a simple key-value store.
Next, we'll define functions to handle the basic operations.
write(key, value)
function to store data: This function will write the data into the dictionary. The 'key' will serve as the unique identifier for the data, sort of like a primary key in a relational database.read(key)
function to fetch data: This function will be used to retrieve data from the dictionary using a key. It's equivalent to a SQL's SELECT statement.update(key, new_value)
function to update data: This function will take a key and new_value and change the existing value of the given key. This is similar to SQL's UPDATE command.delete(key)
function to remove data: This function will remove a key-value pair from the dictionary. This is similar to SQL's DELETE command.
Remember that this is a very basic implementation. Although it lacks features of a fully-fledged relational database, it gives us an idea of how data can be stored and manipulated in a database. At a higher level, real-world databases include additional components like query optimizers, transaction logs, and background cleanup processes, but these basics apply.
xxxxxxxxxx
if __name__ == "__main__":
# Initialize an empty dictionary to be our database
db = {}
# Define our functions
def write(key, value):
db[key] = value
def read(key):
return db.get(key, 'Not Found')
def update(key, new_value):
if key in db:
db[key] = new_value
def delete(key):
if key in db:
del db[key]
# Let's test our database
write('name', 'Alan Turing')
print(read('name')) # Outputs: Alan Turing
update('name', 'Grace Hopper')
print(read('name')) # Outputs: Grace Hopper
delete('name')
print(read('name')) # Outputs: Not Found
print('Program ended')