dbi beginner

How to enable RaiseError and PrintError in Perl DBI connection?

Question

How to enable RaiseError and PrintError in Perl DBI connection?

When using the Perl DBI module, enabling RaiseError and PrintError options during the database connection helps manage errors effectively.

What Do RaiseError and PrintError Do?

  • RaiseError => 1: Makes DBI methods die immediately on errors, stopping execution unless caught. This is useful for robust error checking using eval blocks.
  • PrintError => 1: Prints warnings to STDERR on errors but allows execution to continue. If RaiseError is enabled, it takes precedence and warnings aren't printed.

Common Pitfalls

  • Always include use DBI; in your script, or you will get errors like Can't locate object method "connect" via package "DBI".
  • Choosing between error handling modes depends on your needs; RaiseError simplifies error control but requires eval to catch exceptions.
  • SQLite's in-memory database is great for examples since it requires no setup and no file access.

Working Example: Enable RaiseError and PrintError with SQLite In-Memory

use strict;
use warnings;
use DBI;

my $dsn = "dbi:SQLite:dbname=:memory:";  # In-memory SQLite DB
my $user = "";
my $password = "";

# Connect with RaiseError enabled and PrintError disabled
my $dbh = DBI->connect($dsn, $user, $password, {
    RaiseError => 1,
    PrintError => 0,
    AutoCommit => 1,
}) or die $DBI::errstr;

eval {
    # This will fail because the table does not exist
    $dbh->do("SELECT * FROM non_existent_table");
};
if ($@) {
    print "Caught DBI error: $@\n";
} else {
    print "Query succeeded unexpectedly\n";
}

$dbh->disconnect;

This code demonstrates the key Perl DBI concepts:

  • use DBI; imports the module and enables DBI->connect.
  • The connect call passes a hashref of options including RaiseError => 1 to die on errors automatically.
  • eval catches the exception triggered by the invalid SQL statement.
  • Using SQLite's :memory: DSN creates a temporary, ephemeral database requiring no disk access.

This approach is portable, fast, and safe to run in sandboxed environments without external dependencies, file system, or network access.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 38ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Caught DBI error: DBD::SQLite::db do failed: no such table: non_existent_table at - line 18.

STDERR
(empty)

Was this helpful?

Related Questions