开发者

Suppressing connection error with DBI and DBD:ODBC SQL Server Native Client 10.0

开发者 https://www.devze.com 2023-01-25 15:26 出处:网络
Writing a script to get SQL Server instance names from a table, then attempting to connect to each of these instances to pull back database configuration information. All database instances involved a

Writing a script to get SQL Server instance names from a table, then attempting to connect to each of these instances to pull back database configuration information. All database instances involved are some version of SQL Server. If the connection fails (due to a bad password, instance is down, etc.) the intention is to print a user-defined error message ("Unable to connect to $inst, skipping.") and continue through the list. I'm having trouble suppressing the default error message from ODBC (SQL Server Native Client 10.0).

Connection is attempted like this:

eval {
  my $dbh = DBI->connect(
    "dbi:ODBC:Driver={SQL Server Native Client 10.0};Server=<instance_name>;Uid=<user_name>;Pwd=<password>;",
    { PrintError => 0, RaiseError => 1, AutoCommit => 1 }
  );
};

It is my (probably incorrect) understanding that PrintError => 0 should suppress the error message and RaiseError => 1 will cause DBI to die if the connect method fails, at which point I can check $@ for the error and print a user-defined message. I have also looked at the HandleError attribute but have not had any success.

Is this a completely unrealistic scenario, or is this a result of the ODBC driver I'm working with?

Per bohica's suggestions, working code looks like:

eval {
  my $dbh = DBI->connect(
    "dbi:ODBC:Driver={SQL Server Native Client 10.0};Server=<instance_name>;",
    "Username",
    "Password",
    { PrintError => 0, RaiseError => 开发者_如何学C1, AutoCommit => 1 }
  );
};

Username and password were moved out of connection string and passed as separate parameters to DBI connect method.


Assuming you fix the problem Pedro mentions then, PrintError=>0 suppresses errors and you might want to look at PrintWarn as well. The RaiseError=>1 will cause the connect to die if the connect fails and in your example the error will be in $@.


connect is a class method; you call it with DBI->connect, which returns a db handle ($dbh in your case).

0

精彩评论

暂无评论...
验证码 换一张
取 消