Perl | Database management using DBI
Last Updated :
18 Jun, 2019
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
Personnel involved in Database Management System Many persons are involved in the design, use, and maintenance of a large database with a few hundred users. Here we will consider people who may be called "Actors on the Scene", whose jobs involve the day-to-day use of a large database. Database Administrators: Administrating the primary (database)
5 min read
DBMS Tutorial â Learn Database Management System Database Management System (DBMS) is a software used to manage data from a database. A database is a structured collection of data that is stored in an electronic device. The data can be text, video, image or any other format.A relational database stores data in the form of tables and a NoSQL databa
7 min read
Perl - DBI(Database Independent) Module | Set - 2 Perl allows the handling of Databases with the help of Perl Scripts. These scripts run with the help of a module known as DBI(Database Independent Interface) module. DBI module provides an API to interact with many databases such as MySQL, Oracle, etc. This module provides a set of variables and met
5 min read
Types of Database Management Systems A Database Management System (DBMS) is a software system that is designed to manage and organize data in a structured manner. It allows users to create, modify, and query a database, as well as manage the security and access controls for that database.What is DBMS?A DBMS (Database Management System)
5 min read
SQL Database Access using R DBI DBI library in R programming is used for intеracting with different types of database systems such as MySQL for different types of professional work like data analysis using R language. Wе can еasily connect to the database, run queries and retrieve results from the database in the R еnvironmеnt wit
6 min read
DBMS Full Form - Database Management System DBMS stands for Database Management System. DBMS is the software that is used to manage databases. For example, MySQL, Oracle, PostgreSQL, etc., are popular commercial DBMSs used in different applications. It is a reliable, easy, and efficient way of data processing and management. History of DBMSIn
3 min read
Introduction of DBMS (Database Management System) A Database Management System (DBMS) is a software solution designed to efficiently manage, organize, and retrieve data in a structured manner. It serves as a critical component in modern computing, enabling organizations to store, manipulate, and secure their data effectively. From small application
8 min read
Master Data Management Master data management (MDM) is the center cycle used to oversee, incorporate, compose, sort, confine, synchronize and advance Master data as indicated by business rules of business, promoting, and operational systems of your organization. It is an innovation empowered discipline in which business a
2 min read
Database Languages in DBMS Databases are essential for efficiently storing, managing, and retrieving large volumes of data. They utilize both software and hardware components. The software provides an interface that enables users or applications to interact with the database, while the hardware consists of servers and storage
10 min read
Structure of Database Management System A Database Management System (DBMS) is software that allows users to define, store, maintain, and manage data in a structured and efficient manner. It acts as an intermediary between data and users, allowing disparate data from different applications to be managed. A DBMS simplifies the complexity o
8 min read