Search Postgresql Archives

Re: Catching errors with Perl DBI

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, 2 Jul 2020 11:03:37 -0400
stan <stanb@xxxxxxxxx> wrote:

> my $sth = $dbh->prepare($stmt);
> my $rv = $sth->execute() or die $DBI::errstr;

that ``or die`` means: if the result of the ``execute`` is false
(which only happens on error), throw an exception (which, as you
noticed, terminates the process unless caught with an ``eval {}`` or
similar construct)

> if ( $rv < 0 ) { print $DBI::errstr; }

Notice that ``$rv`` would never be less than 0: for an ``INSERT``,
it's the number of rows inserted (or a special "0 but true" value in
case no rows were inserted).

So, you can do two things:

* keeping the same style::

    my $rv = $sth->execute(@bind_values);
    if (!$rv) {
        print $sth->errstr;
        # and probably do something useful here ☺
    }

* switching to exceptions everywhere

  Tell DBI you want exceptions::

    my $dbh = DBI->connect(
        $dsn,$user,$password,
        {
            PrintError => 0,
            RaiseErorr => 1,
            PrintWarn  => 0,
            RaiseWarn  => 1,
        }
    );

  then run statements like this::

    eval { $dbh->prepare($stmt)->execute(@bind_values) }
        or do {
            print $@; # the exception is store in this variable
        };

-- 
	Dakkar - <Mobilis in mobile>
	GPG public key fingerprint = A071 E618 DD2C 5901 9574
	                             6FE2 40EA 9883 7519 3F88
	                    key id = 0x75193F88







[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]

  Powered by Linux