Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Create a Simple Database Class Supporting Create, Read, Update and Delete in Python

Create a Simple Database Class Supporting Create, Read, Update and Delete in Python

Document Object Reference Manual Python3 Examples

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

       

print

(

f

"Inserted: {key} -> {value}"

)

   

def

delete

(

self

,

key

)

:

       

if

key

in

self

.

db

:

           

del

self

.

db

[

key

]

           

print

(

f

"Deleted: {key}"

)

       

else

:

           

print

(

f

"Key {key} not found."

)

   

def

update

(

self

,

key

,

value

)

:

       

if

key

in

self

.

db

:

           

self

.

db

[

key

]

=

value

           

print

(

f

"Updated: {key} -> {value}"

)

       

else

:

           

print

(

f

"Key {key} not found."

)

   

def

select

(

self

,

key

)

:

       

if

key

in

self

.

db

:

           

print

(

f

"Selected: {key} -> {self.db[key]}"

)

       

else

:

           

print

(

f

"Key {key} not found."

)

   

def

show_all

(

self

)

:

       

print

(

"Database Contents:"

)

       

for

key

,

value

in

self

.

db

.

items

(

)

:

           

print

(

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:

  1. __init__ method initializes an empty dictionary db to store the data.
  2. insert method adds a new key-value pair to the database.
  3. delete method deletes the key-value pair with the specified key.
  4. update method updates the value of the specified key.
  5. select method queries the value of the specified key.
  6. show_all method 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

Document Object Reference Manual Python3 Examples