Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Catch connection error MSSQL

by Anonymous Monk
on Oct 09, 2018 at 13:30 UTC ( #1223732=perlquestion: print w/replies, xml ) Need Help??
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 (Monsignor) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1223732]
Approved by marto
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2018-10-21 17:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When I need money for a bigger acquisition, I usually ...














    Results (119 votes). Check out past polls.

    Notices?