Open In App

Perl | DBI(Database Independent Interface) Module Set – 1

Improve
Improve
Like Article
Like
Save
Share
Report

The database is a collection of inter-related data which helps in efficient retrieval, insertion, and deletion of data from the database and organizes the data in the form of tables, views, schemas, reports, etc. For Example, a university database organizes the data about students, faculty, and admin staff, etc. which helps performing operations on this data more efficiently.

This database can be accessed and manipulated with the help of various tools and software. In Perl, the database can be accessed and manipulated 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 methods that provide interaction with a database interface and need not to access the original database.

Note: DBI doesn’t perform any operation on the database. It just provides a layer between the application and the drivers. With the use of this layer, the drivers interact and perform operations on the application.

Architecture of a Perl DBI

DBI in Perl doesn’t depend on what database it’s using. It takes commands and instructions from the API and forwards them to the Drivers associated to it.

Connecting DBI to a database in Perl

To connect to a database in Perl, one must have a database server installed on the system. Here, we are using MySQL, so further instructions will be relevant to the MySQL database.

First: You need to install DBI module of Perl in your system. This can be done by running the following command in your Shell to install the DBI module:

perl -MCPAN -e shell
install DBI


Second: Start your MySQL server and follow the next steps to make a connection with your DBI:

Step 1: Create a database and name it accordingly. Here, we are going to name it as ‘GFG’.
Step 2: Create a table inside this database. We have created a table ‘Employee’ with the fields as ‘Name’, ‘Designation’, and ‘Salary’.
Step 3: Use the following given script to connect the database with Perl File:




#!/usr/bin/perl  
use strict;  
use warnings;  
use DBI;  
  
my $driver = "mysql";  
my $database = "GFG";  
my $dsn      = "dbi:$driver:database=$database";  
my $user     = "root";  
my $password = "";  
my $dbh = DBI->connect($dsn, $user, $password
{  
   PrintError       => 0,  
   RaiseError       => 1,  
   AutoCommit       => 1,  
   FetchHashKeyName => 'NAME_lc',  
});  
$dbh->disconnect;  


Here in the above script, the variable $dsn holds the database which is being loaded and variable $dbh holds the database handle objects.


Last Updated : 02 Aug, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads