Python - Database Manager (dbm) package
Last Updated :
18 May, 2023
In this article, we will learn about dbm, a package in the built-in library of Python. The dbm package in Python provides a simple dictionary-like interface of the form DBM (DataBase Manager) generally used in the Unix operating system. dbm stores data in simple key-value pair form like a dictionary, making it easier to insert, edit and retrieve data from the database. It stores data using a single primary key ("key") in fixed-size blocks.
There are three types of submodules in dbm package :
- dbm.gnu: GNU’s reinterpretation of dbm
- dbm.ndbm: Interface based on ndbm
- dbm.dumb: Portable DBM implementation
The following are the main functions available in dbm package :
dbm.open()
This function is used to open a dbm database or create a new database if not exist.
Syntax: dbm.open(file, flag='r', mode=0o666)
Parameters: This function take following parameters:
- file: name of the file.
- flag: mode of permissions. which can be 'r', 'w', 'c', or 'n'.
- 'r': open the existing database with permission to read only.
- 'w': open the existing database with permission to read and write.
- 'c': open the database for read and write, also create a new one if it doesn't exists.
- 'n': Always create a new database with permission to both read and write.
- mode: The Unix mode of the argument which is a octal form default set to 0o666, used only when new database is to be created.
Return: The corresponding object address of the database file.
dbm.whichdb()
This function attempts to guess which of the several simple database modules available- dbm.gnu, dbm.ndbm, or dbm.dumb- should be used to open a given file.
Syntax: dbm.whichdb(filename)
Parameter: filename- Name of the file.
Returns: The function returns one of the following values :
- None: If the database doesn't exists or it can't be opened.
- (' '): An empty string, if the file exists but the file format can't be guessed else
- The required module name: If the type is successfully detected then one of the string names is returned, 'dbm.gnu', 'dbm.ndbm' or 'dbm.dumb'.
Following are the built-in methods for dbm objects :
- open(filename): This method will open the file of the database whose name is passed as the parameter.
- whichdb(filename): Returns the database module used to open the file provided as parameters.
- get(key): Returns the value corresponding to key given in argument.
- keys(): Returns an iterable list containing keys of the dictionary.
- firstkey(): It returns the starrting key.
- nextkey(key): It returns the key that is next to the current key which is passed as arguments.
- setdefault(): set a default primary key given in the argument.
- reorganize(): Reorganises the databse to increase space y compacting the data.
- error(): A tuple conatining exceptions that are raised when some error is occured while executing dbm module.
- sync(): Helps to synchronize data files and on disk directory.
- close(): Doesn't take any argument nor returns anything. Just closes the caller object database. (db in this case)
Below is the implementation of all the above-discussed methods/functions:
Code:
Python3
# importing the dbm package
import dbm
# using the open function
# to create a new database named
# 'mydb' in 'n' mode, object
# returned in db variable.
db = dbm.open('mydb','n')
# inserting the new key and
# values in the database.
db['name'] = 'GeeksforGeeks'
db['phone'] = '8888'
db['Short name'] = 'GfG'
db['Date'] = '01/01/2000'
# getting and printing
# the value through get method.
print(db.get('name'))
print()
# printing the values of
# database through values()
# method (iterator).
for value in db.values():
print(value)
print()
# printing the values through
# key iterator.
for key in db.keys():
print(db.get(key))
print()
# popping out the key, value
# pair corresponding to
# 'phone' key.
db.pop('phone')
# printing the key, value
# pairs present in database.
for key, value in db.items():
print(key, value)
# clearing all the key values
# in database.
db.clear()
# Below loop will print nothing
# as database is cleared above.
for key, value in db.items():
print(key, value)
# closing the database.
db.close()
# This code is contributed by Amit Mangal.
Output :
b'GeeksforGeeks'
b'GeeksforGeeks'
b'8888'
b'GfG'
b'01/01/2000'
b'GeeksforGeeks'
b'8888'
b'GfG'
b'01/01/2000'
b'name' b'GeeksforGeeks'
b'Short name' b'GfG'
b'Date' b'01/01/2000'
Similar Reads
Python | Database management in PostgreSQL PostgreSQL is an open source object-relational database management system. It is well known for its reliability, robustness, and performance. PostgreSQL has a variety of libraries of API (Application programmable interface) that are available for a variety of popular programming languages such as Py
6 min read
Describing Databases with MetaData - SQLAlchemy In this article, we are going to see how to describe Databases with MetaData using SQLAlchemy in Python. Database Metadata describes the structure of the database in terms of Python data structures. The database usually consists of Tables and Columns. The Database Metadata serves us in generating SQ
6 min read
Python MySQL - Create Database Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000,
2 min read
How to integrate Mysql database with Django? Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database â SQLlite3, etc. Installation Let's first un
2 min read
Multiple Postgres databases in psycopg2 PostgreSQL is the most powerful open-source object-relational database management system. Psycopg2 is the most popular PostgreSQL database adapter for Python language. It simply allows you to work with multiple databases in the same program at the same time. This indicates that you can easily switch
4 min read
Django manage.py migrate command | Python According to documentation, Migrations are Djangoâs way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. Theyâre designed to be mostly automatic, but youâll need to know when to make migrations when to run them, and the common problem
2 min read
How to use PostgreSQL Database in Django? This article revolves around how can you change your default Django SQLite-server to PostgreSQL. PostgreSQL and SQLite are the most widely used RDBMS relational database management systems. They are both open-source and free. There are some major differences that you should be consider when you are
2 min read
Create a database in MongoDB using Python MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud. It is a document database, which means it stores data in JSON-like documents. This is an efficient way to think about data and is more expressive and powerful than the traditiona
2 min read
Create Database in MariaDB using PyMySQL in Python MariaDB is an open source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python. In this article we will look into the process of creating a database using pymysql. To create a database use the below syn
2 min read
DatabaseError in Django In this article, we will elucidate the 'django.db.utils.DatabaseError' by explaining. We will delve into the reasons behind the occurrence of this error and explore various approaches to handle it effectively. What is 'django.db.utils.DatabaseError ' ?The 'django.db.utils.DatabaseError' is an except
4 min read