Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Perl Index

🗄️ DBI — Database interface — MySQL, PostgreSQL, SQLite, Oracle

Perl's DBI is the universal database interface. Combine with DBD::mysql, DBD::Pg, DBD::SQLite, or DBD::Oracle driver modules. Always use placeholders to prevent SQL injection.

📋 Functions & Syntax

NameSignatureDescription
DBI->connectDBI->connect($dsn, $user, $pass, \%attr) → $dbhConnect to database
$dbh->prepareprepare($sql) → $sthPrepare SQL statement
$sth->executeexecute(@bind_values) → boolExecute prepared statement
$sth->fetchrow_arrayreffetchrow_arrayref() → \@rowFetch next row as array ref
$sth->fetchrow_hashreffetchrow_hashref() → \%rowFetch next row as hash ref
$sth->fetchall_arrayreffetchall_arrayref() → \@rowsFetch all rows
$sth->fetchall_hashreffetchall_hashref($key) → \%hFetch all rows keyed by column
$dbh->dodo($sql, undef, @binds) → $rowsExecute single SQL statement
$dbh->selectall_arrayrefselectall_arrayref($sql, \%attr, @binds)Select and fetch all
$dbh->selectrow_hashrefselectrow_hashref($sql, \%attr, @binds)Select single row as hashref
$dbh->last_insert_idlast_insert_id(undef,undef,undef,undef)Get last auto-increment ID
$dbh->begin_workbegin_work() → boolStart transaction
$dbh->commitcommit() → boolCommit transaction
$dbh->rollbackrollback() → boolRoll back transaction
$dbh->disconnectdisconnect()Close database connection
RaiseError{ RaiseError => 1 }Auto-die on DB errors (recommended)
AutoCommit{ AutoCommit => 1/0 }Auto-commit mode
Slice{ Slice => {} }Return rows as hashrefs in selectall_arrayref
dbi:SQLitedbi:SQLite:dbname=file.dbSQLite DSN — no server needed
dbi:mysqldbi:mysql:database=mydb;host=localhostMySQL/MariaDB DSN
dbi:Pgdbi:Pg:dbname=mydb;host=localhostPostgreSQL DSN

💡 Example

Run with perl script.pl.

#!/usr/bin/perl
use strict;
use warnings;
use DBI;

my $dbh = DBI->connect("dbi:SQLite:dbname=university.db", "", "",
                        { RaiseError => 1, AutoCommit => 1 })
    or die "Connect failed: $DBI::errstr";

$dbh->do(q{CREATE TABLE IF NOT EXISTS students (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL, subject TEXT NOT NULL, score INTEGER NOT NULL)});

my $insert = $dbh->prepare(
    "INSERT INTO students (name, subject, score) VALUES (?, ?, ?)");
$insert->execute(@$_) for
    (["Alice","Math",95],["Bob","Science",87],["Carol","Math",92],
     ["Dave","Science",78],["Eve","Math",98]);

print "=== All students ===\n";
my $rows = $dbh->selectall_arrayref(
    "SELECT name, subject, score FROM students ORDER BY score DESC",
    { Slice => {} });
printf "  %-10s %-10s %d\n", $_->{name}, $_->{subject}, $_->{score} for @$rows;

print "=== Average by subject ===\n";
my $sth = $dbh->prepare(
    "SELECT subject, AVG(score) avg, COUNT(*) cnt FROM students GROUP BY subject");
$sth->execute();
while (my $row = $sth->fetchrow_hashref) {
    printf "  %-10s avg=%.2f cnt=%d\n", $row->{subject}, $row->{avg}, $row->{cnt};
}

eval {
    $dbh->begin_work;
    $dbh->do("UPDATE students SET score = score + 2 WHERE subject = 'Science'");
    $dbh->commit;
    print "Transaction committed.\n";
};
if ($@) { $dbh->rollback; die "Rolled back: $@"; }

$dbh->disconnect;
unlink "university.db";
print "Done.\n";
# perl dbi_demo.pl  (requires: cpan install DBI DBD::SQLite)

← File IO  |  🏠 Index