http://www.perlmonks.org?node_id=1223732

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I want to connect to a MSSQL server and catch a connection error if it happens. I used to use on MySQL an eval which, as far as I remember worked fine. However, I can not catch an error if it happens now, if for example the password is wrong. This is what I am using:

print "Connecting to MSSQL terminology database... "; eval{ $dbh = DBI->connect("dbi:ODBC:Driver={SQL Server};Server=$SqlDatabase +Name;UID=$SqlDatabaseUser;PWD=$SqlDatabasePassword", {PrintError => 0 +, RaiseError => 1, AutoCommit => $AutoCommit, FetchHashKeyName => 'NA +ME_lc',}) ; $dbh->{'mysql_enable_utf8'} = 1; }; if ($@) { print "ERRRRRRRRRRRROR\n"; }

Any idea what I am doing wrong?

Replies are listed 'Best First'.
Re: Catch connection error MSSQL
by FloydATC (Deacon) on Oct 09, 2018 at 13:52 UTC

    I have not tested this with MSSQL, only MySQL but you should be able to just use RaiseError => 0 and then check $DBI::errstr instead of $@. Note the difference between this and $dbh->errstr which will not work if $dbh is undef for whatever reason.

    -- FloydATC

    I got 99 problems, most of them have to do with printers.

Re: Catch connection error MSSQL
by 1nickt (Canon) on Oct 09, 2018 at 15:15 UTC

    Hi, maybe $@ is getting clobbered somewhere. Try Try::Tiny:

    use Try::Tiny; print "Connecting to MSSQL terminology database... "; try { $dbh = DBI->connect("dbi:ODBC:Driver={SQL Server};Server=$SqlDatabase +Name;UID=$SqlDatabaseUser;PWD=$SqlDatabasePassword +", {PrintError => 0, RaiseError => 1, AutoCommit => $AutoCommit, Fetc +hHashKeyName => 'NAME_lc',}) ; $dbh->{'mysql_enable_utf8'} = 1; } catch { print "ERRRRRRRRRRRROR: $_\n"; # error in $_ };

    Hope this helps!


    The way forward always starts with a minimal test.
Re: Catch connection error MSSQL
by Anonymous Monk on Oct 10, 2018 at 22:01 UTC

    Both suggested solutions work (and the original one too) if I add a or die to the connect statement. I am not sure why. The script keeps running but the "Died" message is passed.