Create a simple database class in Python that supports add, delete, update, and query operations
We will create a simple database classSimpleDB, which uses Python dictionaries to simulate database tables. This class will support basic add, delete, update, and query 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()
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:
__init__The method initializes an empty dictionarydbto store data.insertThe method is used to add new key-value pairs to the database.deleteThe method is used to delete the key-value pair of the specified key.updateThe method is used to update the value of the specified key.selectThe method is used to query the value of the specified key.show_allThe method is used to display 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 -> AliceOther extensions
Python3 Examples