How to create Database Connection in Perl?


Assuming we are going to work with MySQL database with Perl. Before connecting to a database make sure of the followings. You can take help of our MySQL tutorial in case you are not aware about how to create database and tables in MySQL database.

  • You have created a database with a name TESTDB.
  • You have created a table with a name TEST_TABLE in TESTDB.
  • This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
  • User ID "testuser" and password "test123" are set to access TESTDB.
  • Perl Module DBI is installed properly on your machine.
  • You have gone through MySQL tutorial to understand MySQL Basics.

Following is the example of connecting with MySQL database "TESTDB" −

#!/usr/bin/perl
use DBI
use strict;
my $driver = "mysql";
my $database = "TESTDB";
my $dsn = "DBI:$driver:database=$database";
my $userid = "testuser";
my $password = "test123";
my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;

If a connection is established with the datasource then a Database Handle is returned and saved into $dbh for further use otherwise $dbh is set to undef value and $DBI::errstr returns an error string.

Disconnecting Database

To disconnect Database connection, use disconnect API as follows −

$rc = $dbh->disconnect or warn $dbh->errstr;

The transaction behaviour of the disconnect method is, sadly, undefined. Some database systems (such as Oracle and Ingres) will automatically commit any outstanding changes, but others (such as Informix) will rollback any outstanding changes. Applications not using AutoCommit should explicitly call commit or rollback before calling disconnect.

raja
Published on 02-Dec-2019 07:45:13
Advertisements