Create a Simple Database Class Supporting Create, Read, Update and Delete in Python
We will create a simple database class SimpleDBthat uses a Python dictionary to simulate a database table. The class supports basic create, read, update and delete operations.
Example
class
SimpleDB:
def
init
(
self
)
:
self
.
db
=
{
}
def
insert
(
self
,
key
,
value
)
:
self
.
db
[
key
]
=
value
(
f
"Inserted: {key} -> {value}"
)
def
delete
(
self
,
key
)
:
if
key
in
self
.
db
:
del
self
.
db
[
key
]
(
f
"Deleted: {key}"
)
else
:
(
f
"Key {key} not found."
)
def
update
(
self
,
key
,
value
)
:
if
key
in
self
.
db
:
self
.
db
[
key
]
=
value
(
f
"Updated: {key} -> {value}"
)
else
:
(
f
"Key {key} not found."
)
def
select
(
self
,
key
)
:
if
key
in
self
.
db
:
(
f
"Selected: {key} -> {self.db[key]}"
)
else
:
(
f
"Key {key} not found."
)
def
show_all
(
self
)
:
(
"Database Contents:"
)
for
key
,
value
in
self
.
db
.
items
(
)
:
(
f
"{key} -> {value}"
)
Example usage
db
=
SimpleDB
(
)
db.
insert
(
'name'
,
'Alice'
)
db.
insert
(
'age'
,
30
)
db.
show_all
(
)
db.
update
(
'age'
,
31
)
db.
select
(
'name'
)
db.
delete
(
'age'
)
db.
show_all
(
)
Code analysis:
__init__method initializes an empty dictionarydbto store the data.insertmethod adds a new key-value pair to the database.deletemethod deletes the key-value pair with the specified key.updatemethod updates the value of the specified key.selectmethod queries the value of the specified key.show_allmethod displays all key-value pairs in the database.
Output result:
Inserted: name -> Alice
Inserted: age -> 30
Database Contents:
name -> Alice
age -> 30
Updated: age -> 31
Selected: name -> Alice
Deleted: age
Database Contents:
name -> Alice
Python3 Examples