Databases are essential for the Internet and its services. They store data in an organized and structured way, usually in tables with rows and columns. Databases can be accessed and manipulated in Python using the specified database manager package called “dbm”. The “dbm” package can create databases and perform operations on them using various functions and methods. It works with databases without requiring any external dependencies.
The write-up will deliver you a comprehensive overview of the Python DBM database using the below contents:
What is the Database Manager (dbm) in Python?
Database Manager (dbm) Module Types in Python
Functions and Methods of dbm Module in Python
-
- Example 1: Inserting and Retrieving Value Using dbm.open() and dbm.get()
- Example 2: Retrieving Values Using “dbm.values()” Method
- Example 3: Retrieving Values Using Key Iterator
- Example 4: Popping Key-Value Pair Using “dbm.pop()” Method
- Example 5: Clearing All Key-Value Pairs Using “dbm.clear()”
- Example 6: Opening dbm File Using the “dbm.whichdb()” Function
What is the Database Manager (dbm) in Python?
In Python, the Database Manager (dbm) package is a built-in library that delivers a simple dictionary-like interface for working with databases. It is commonly used in the Unix operating system and keeps data in a key-value pair format. The “dbm” package is a database library that acts as a database manager in a Python program. It is used by users to work with data in a structured manner.
Database Manager (dbm) Module Types in Python
There are three different module types of Database managers in Python:
dbm.gnu
This is a GNU reinterpretation of dbm and delivers additional functionality using the GNU library gdbm. The file created by dbm.gnu and dbm are incompatible.
dbm.ndbm
This submodule provides an interface based on the ndbm implementation.
dbm. dumb
This portable dbm implementation is written entirely in Python and is used as a fallback option when other dbm implementations are not found. It is slower than the other submodules but does not need any outer dependencies.
Functions and Methods of dbm Module in Python
There are various functions and methods that are available in the dbm package. We will discuss some of the functions including their example:
Example 1: Inserting and Retrieving Value Using dbm.open() and dbm.get()
The “dbm.open()” function is employed in Python to open a dbm database or construct a new database if it does not present/exist. Similarly the “dbm.get()” method is used to retrieve the value from the created database.
Syntax
Parameters
In the above syntax, the “file” parameter determines the file name. The “flag” parameter specifies the mode of permission. The “mode” parameter is an octal form of Unix mode and is used while creating a new database.
Modes of Opening File
The following are modes flags used while opening the database file:
Flags | Description |
r | Read-only |
w | Read and write |
c | Read and write, creating the database if it does not exist |
n | This flag always constructs a new empty database. It also opens database files for reading and writing. |
Return Value
The “dbm.open()” function retrieved the database file object address.
Now, let’s implement this function with the following example:
# using the open function
data_base = dbm.open('new','n')
# Inserting the new key and value
data_base['Name'] = 'Linuxhint'
data_base['Age'] = '23'
data_base['Height'] = '5.7'
data_base['Date'] = '11/02/1992'
# Getting and printing the value through the get method.
print(data_base.get('Name'))
print(data_base.get('Age'))
print()
Here, we imported the dbm package. Next, the “dbm.open()” function creates the new database file named “new”. After that, we insert the new key with their value into the database file. In the end, we print the value through the “dbm.get()” method.
Output
The output shows the retrieved value of the database.
Example 2: Retrieving Values Using “dbm.values()” Method
We can also utilize the “dbm.values()” method to retrieve the values:
for i in data_base.values():
print(i)
print()
In this code, the “for loop” is utilized to iterate over the retrieved value of the “dbm.values()” method. Next, the “print()” function is used to print each key value of the database.
Output
The specified key value of the database file is shown to the console output.
Example 3: Retrieving Values Using Key Iterator
Instead of using the “dbm.values()” method. You can also use the “dbm.key()” method to retrieve the value of the key from the database.
for key in data_base.keys():
print(data_base.get(key))
print()
Here the “for loop” loops through the “dbm.key()” method that retrieves all the keys of the database. After that the “dbm.get()” method retrieves the values for each key and displays them to the output by print() function.
Output
Example 4: Popping Key-Value Pair Using “dbm.pop()” Method
The “dbm.pop()” method can be utilized to remove the particular key-value pair from the specified database.
data_base.pop('Height')
# Displaying the database key-value.
for key, value in data_base.items():
print(key, value)
In the above code, the “dbm.pop()” method takes the “Height” key as an argument and removes them from the database including the value. After removing the value, we retrieved the remaining key-value pair from the database using the for loop and the “dbm.items()” method.
Output
Example 5: Clearing All Key-Value Pairs Using “dbm.clear()”
Sometimes, we are required to clear all the key-value pairs from the input database file. To do this, the “dbm.clear()” method is utilized in Python.
data_base.clear()
# printing database.
for key, value in data_base.items():
print(key, value)
data_base.close()
Here, in this code, the “clear()” method clears all the key-value pairs from the database. To verify the clearing, the “for loop” iterates over the value of the item retrieved from the “dbm.items()” method.
Output
The above output varies that the given database has been declared.
Example 6: Opening dbm File Using the “dbm.whichdb()” Function
In Python, the “dbm.whichdb()” function estimates which of the multiple simple database modules found (dbm.gnu, dbm.ndbm, or dbm.dumb) and should be used to open the input file.
Syntax
The above syntax accepts the filename argument and retrieves the “None”, “empty string” and the string containing the “module name”.
Now. let’s understand this via the below example:
# using the whichdb function
data_base = dbm.whichdb('new')
print(data_base)
In this code, the “dbm.whichdb()” method accepts the filename and retrieves the specific module name, which will be displayed to the output using the “print()” function.
Output
Some Other Built-in Methods for dbm Objects
There are other modules that can be used to perform specified operations on dbm objects. Here are some of them:
Methods | Descriptions |
firstkey() | This method is used to loop over every key in the database. |
nextkey() | This method is used to retrieve the key that is next to the present key input as an argument. |
setdefault() | This method sets a default primary key specified in the parameter/argument. |
reorganize() | This method reorganizes the database if a lot of deletions have been carried out and the space used by the gdbm file needs to be shrunk. |
error() | This method raises an exception on dbm-specific errors. |
synx() | This method synchronizes the database with the file on disk. |
Conclusion
In Python, the “dbm” module is utilized to work with the database object by supporting the dictionary-like interface with a key-value pair format. The different methods of the Python “dbm” package such as dbm.open(), dbm.values(), dbm.firstkey(), and others are used to perform multiple operations on dbm objects. This guide provided several examples of Python dbm modules with code explanations.