Perl | Database management using DBI
Last Updated :
12 Jul, 2025
Prerequisites:
Creating database programs is one of the most common uses of Perl. Using Perl, we can create robust web applications along with a database to manage all the data. It provides excellent support for interfacing and a broad range of database formats. For connecting to and querying a database, Perl provides a module called
DBI. DBI is a database interface for communicating with database servers that use
Structured Query Language (SQL) to get data.
Accessing a Database in Perl generally takes two steps. The DBI module provides an
API for database access. A program uses the functions of DBI to manipulate the database. The second stage of database access from Perl is a
database driver (DBD) module. Each different database system requires its own driver. This approach allows a Perl database application program to be relatively independent of the particular database it will access.
Installation: To Install DBI module, open terminal and type the following command and press Enter:
perl -MCPAN -e 'install Bundle::DBI'
This will automatically download and Install the driver for the DBI module to provide database connectivity with Perl.
Database Independent Interface(DBI)
As the name suggests, DBI provides an independent interface for Perl programs. This means that the Perl code doesn't depend on the database running in the backend. DBI module provides
abstraction, i.e, we can write our code without worrying about the database that runs in the back-end.
To import the functions of the Database Independent Interface module, we need to import or include the module with the help of "use" pragma. The
use DBI
pragma allows us to use
DBI module to manipulate the database that we are connecting to.
Syntax: use DBI;
Connecting to the database:
The
connect()
method is used to connect to the specified database. It takes three arguments:
- A string of three values separated by a ':' in this example, it is "DBI:mysql:test". The first value specifies that we are using DBI. the second value specifies the database engine, which, in this case, is MySQL. the third value specifies the name of the database that you want to connect to.
- The next argument to the connect() method is the username. In this case, user is 'root'.
- The last argument is the password of your local system. In this example, it is 'password'
Syntax:
my $dbh = DBI->connect ("DBI:mysql:test", "root", "password") or die "Can't connect: " . DBI->errstr();
The "or die" statement terminates the program if it was unable to establish a connection with the database, with an error message. The
errstr()
method returns a string that contains any errors encountered when connecting to the database.
Preparing Queries:
The
prepare()
method takes in one parameter, the SQL query to be executed. The SQL query is taken in the form of a string that contains the SQL statement. This SQL statement is the same as the SQL statements that you would execute in MySQL. It returns an object called a statement handle that can be used to execute queries.
Syntax:
my $sth = $dbh->prepare( " CREATE TABLE emp( id INT PRIMARY KEY, name VARCHAR(10), salary INT, ");
Now, the query is prepared for execution. Note that in the above query, we are creating a
table with
id,
name and
salary columns.
Executing the queries:
The
execute()
method executes the query written in the
prepare()
method. It does not take any arguments. It is called using the statement handle object created when the '
prepare' statement is executed.
Syntax:
$sth->execute();
Fetching Values from the result:
The
fetchrow()
method is used to retrieve the next row of data from the result of the executed query. If a select query is executed, then the
fetchrow()
method fetches the next row from the result. It returns one row from the result which can be assigned to variables. When used in a while loop, we can fetch and display all the rows in the database using the
fetchrow()
method.
Syntax:
($id, $name, $salary) = $sth->fetchrow();
The values of each column are stored in the three variables.
The
fetchrow_array()
function returns an array that contains the row from the result
Syntax:
my @row = $sth->fetchrow_array( )
Disconnecting:
Once all the queries are executed, we need to disconnect the connection. This is done by the use of
disconnect()
function. Doing so allows the Perl script to properly terminate the connection. Not disconnecting from the database will not generate any errors. It is generally a good practice to do so.
Syntax:
$dbh->disconnect();
Creating the database in MySQL:
MySQL must be installed in your system and basic knowledge of MySQL is required.
- Log in to your MySql server
- Create a Database called "test". We will connect to this database so make sure that the
name is "test"
- Make sure that this database has no tables as we will be creating a table called "emp" and
insert values into this table
Putting it all together:
Once you have created the database in
MySQL, we can access that database in Perl. We first create an emp table in the database called test with the schema: (
id INTEGER PRIMARY KEY,
name VARCHAR(10),
salary INT,
dept INT). Once the table is created without any errors, we insert values into the table.
Once the values are inserted, we can query the table to select all the rows and display them to the user using the
fetchrow()
function.
Example:
PERL
#!/usr/bin/perl -w
use DBI;
# definition of variables
# name of the database. In this case,
# the name of the database in my local
# system is test.
# user in this case is root
$user = "root";
# this is the password for root
$password = "password";
# connect to MySQL database
my $dbh = DBI->connect ("DBI:mysql:test",
$user,
$password)
or die "Can't connect to database: $DBI::errstr\n";
print "connected to the database\n";
# the test database contains a table called emp
# the schema : (id INTEGER PRIMARY KEY,
# name VARCHAR(10), salary INT, dept INT)
# let us first insert some values
# prepare the query to
# create the emp table
my $sth = $dbh->prepare("CREATE TABLE emp(id INT PRIMARY KEY,
name VARCHAR(10),
salary INT, dept INT)");
# execute the query
# now, the table is created
$sth->execute();
# prepare the query
my $sth = $dbh->prepare("INSERT INTO emp
VALUES(?, ?, ?, ?)");
# define the variables to be inserted
# into the table
my $id = 1;
my $name = "adith";
my $salary = 1000;
my $dept = 2;
# insert these values into the emp table.
$sth->execute($id, $name, $salary, $dept);
# insert some more rows into the table.
$sth->execute($id + 1, $name,
$salary + 100, $dept - 1);
# insert more rows
$sth->execute($id + 2, "Tyrion",
$salary + 1000, $dept + 1);
print "Successfully inserted values into the table\n";
# now, select all the rows from the table.
my $sth = $dbh->prepare("SELECT * FROM emp");
# execute the query
$sth->execute();
# Retrieve the results of a row of data and print
print "\tQuery results:\n================================================\n";
# fetch the contents of the table
# row by row using fetchrow_array() function
while (my @row = $sth->fetchrow_array())
{
print "@row\n";
}
# if the function cannot be execute, show a warning.
warn "Problem in retrieving results", $sth->errstr( ), "\n"
if $sth->err();
print "\n";
# select particular columns.
# prepare the query
my $sth = $dbh->prepare("SELECT name, salary FROM emp");
# execute the query
$sth->execute( );
# Retrieve the results of a row of data and print
print "\tQuery results:\n================================================\n";
while(($name, $sal) = $sth->fetchrow_array())
{
print "Name: $name, salary: $sal\n";
}
warn "Problem in retrieving results", $sth->errstr( ), "\n"
if $sth->err( );
# end of program
exit;
Output :
Similar Reads
Basics
Perl Programming LanguagePerl is a general purpose, high level interpreted and dynamic programming language. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++. Since Perl is a lot similar to other widely used lan
3 min read
Introduction to PerlPerl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used expansion is "Practical Extraction and Reporting Language". Some of the programmers also refer Perl as the
9 min read
Perl Installation and Environment Setup in Windows, Linux, and MacOSPrerequisite: Introduction to Perl Before, we start with the process of Installing Perl on our System, whether it be Windows, Linux or Macintosh. We must have first-hand knowledge of What the Perl Language is and what it actually does?. Perl is a general purpose, high level interpreted and dynamic p
3 min read
Perl | Basic Syntax of a Perl ProgramPerl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and
10 min read
Hello World Program in PerlPerl programming language is exclusively designed for text processing purposes. Its abbreviation denotes Practical Extraction and Report Language. It is compatible on various platforms, such as Windows, Mac OS, and almost all versions of UNIX. Hello World! program in every programming language gives
3 min read
Fundamentals
Control Flow
Perl | Decision Making (if, if-else, Nestedâif, if-elsif ladder, unless, unless-else, unless-elsif)Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These
6 min read
Perl | Loops (for, foreach, while, do...while, until, Nested loops)Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the pro
7 min read
Perl | given-when Statementgiven-when statement in Perl is a substitute for long if-statements that compare a variable to several integral values. The given-when statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. given is a c
4 min read
Perl | goto statementThe goto statement in Perl is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function. Syntax: LABEL: Statement 1; Statement 2; . . . . . Statement n; goto LABEL; In the above syntax, the
3 min read
Arrays & Lists
Perl | ArraysIn Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Example: @number = (50, 70, 46); @names = ("Geeks", "For",
6 min read
Perl | Array SlicesIn Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Arrays can store any type of data and that data can be acce
3 min read
Perl | Arrays (push, pop, shift, unshift)Perl provides various inbuilt functions to add and remove the elements in an array. .string-table { font-family: arial, sans-serif; border-collapse: collapse; border: 1px solid #5fb962; width: 100%; } .string-table td, th { background-color: #c6ebd9; border: 1px solid #5fb962; text-align: left; padd
3 min read
Perl List and its TypesIntroduction to Lists A list is a collection of scalar values. We can access the elements of a list using indexes. Index starts with 0 (0th index refers to the first element of the list). We use parenthesis and comma operators to construct a list. In Perl, scalar variables start with a $ symbol wher
4 min read
Hash
Scalars
Strings
Perl | Quoted, Interpolated and Escaped StringsA string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers, special characters. The string can consist of a single word, a group of words or a multi-line paragraph. The String is defined by the user within a single quote (â) or double quote (â). Quoted Stri
4 min read
Perl | String OperatorsOperators are the foundation of any programming language. Thus, the functionality of Perl programming language is incomplete without the use of operators. A user can define operators as symbols that help to perform specific mathematical and logical computations on operands. String are scalar variabl
4 min read
Perl | String functions (length, lc, uc, index, rindex)String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follow
4 min read
OOP Concepts
Object Oriented Programming (OOPs) in PerlObject-oriented programming: As the name suggests, Object-Oriented Programming or OOPs refers to languages that uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind to
7 min read
Perl | Classes in OOPIn this modern world, where the use of programming has moved to its maximum and has its application in each and every work of our lives, we need to adapt ourselves to such programming paradigms that are directly linked to the real-world examples. There has been a drastic change in the competitivenes
6 min read
Perl | Objects in OOPsPerl is an Objected Oriented, dynamic and interpreter based programming language. In object-oriented programming, we have three main aspects, which are, object, class, and methods. An object is a data type which can be specifically called as an instance of the class to which it belongs. It can be a
6 min read
Perl | Methods in OOPsMethods are used to access and modify the data of an object. These are the entities which are invoked with the use of objects of a class or a package itself. Methods are basically a subroutine in Perl, there is no special identity of a method. Syntax of a method is the same as that of a subroutine.
5 min read
Perl | Constructors and DestructorsConstructors Constructors in Perl subroutines returns an object which is an instance of the class. In Perl, the convention is to name the constructor "new". Unlike many other OOPs, Perl does not provide any special syntax for constructing an object. It uses Data structures(hashes, arrays, scalars) t
4 min read
Perl | Method Overriding in OOPsIn any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signat
6 min read
Perl | Inheritance in OOPsInheritance is a key concept in object-oriented programming that allows you to define a new class based on an existing class. The new class, called a subclass or derived class, inherits all of the properties and methods of the existing class, called the superclass or base class, and can also define
7 min read
Perl | Polymorphism in OOPsPolymorphism is the ability of any data to be processed in more than one form. The word itself indicates the meaning as poly means many and morphism means types. Polymorphism is one of the most important concepts of object-oriented programming languages. The most common use of polymorphism in object
4 min read
Perl | Encapsulation in OOPsEncapsulation in Perl is the process of wrapping up of data to protect it from the outside sources which need not have access to that part of the code. Encapsulation is a part of the Object-oriented programming, it is used to bind the data and the subroutines that are used to manipulate that data. I
6 min read
Regular Expressions
File Handling
Perl | File Handling IntroductionIn Perl, file handling is the process of creating, reading, writing, updating, and deleting files. Perl provides a variety of built-in functions and modules that make it easy to work with files. Here's an introduction to file handling in Perl: File modes:When opening a file in Perl, you need to spec
7 min read
Perl | Opening and Reading a FileA filehandle is an internal Perl structure that associates a physical file with a name. All filehandles have read/write access, so once filehandle is attached to a file reading/writing can be done. However, the mode in which file handle is opened is to be specified while associating a filehandle. Op
4 min read
Perl | Writing to a FileA filehandle is a variable that is used to read and write to a file. This filehandle gets associated with the file. In order to write to the file, it is opened in write mode as shown below: open (FH, â>â, âfilename.txtâ); If the file is existing then it truncates the old content of file with the
3 min read
Perl | Useful File-handling functionsPerl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. These operations can be performed by the use of various inbuilt file functions. Example: Perl #!/usr/bin/perl # Opening a
2 min read