[英]Suppressing connection error with DBI and DBD:ODBC SQL Server Native Client 10.0
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. 编写脚本以从表中获取SQL Server实例名称,然后尝试连接到每个这些实例以拉回数据库配置信息。 All database instances involved are some version of SQL Server.
涉及的所有数据库实例都是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.
如果连接失败(由于密码错误,实例关闭等),目的是打印用户定义的错误消息(“无法连接到$ inst,正在跳过。”)并继续浏览列表。 I'm having trouble suppressing the default error message from ODBC (SQL Server Native Client 10.0).
我无法抑制来自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. 我的理解(可能是不正确的)是PrintError => 0应该抑制错误消息,并且如果connect方法失败,RaiseError => 1将导致DBI死亡,这时我可以检查$ @的错误并打印用户-定义的消息。 I have also looked at the HandleError attribute but have not had any success.
我也查看了HandleError属性,但没有成功。
Is this a completely unrealistic scenario, or is this a result of the ODBC driver I'm working with? 这是完全不现实的情况,还是我正在使用的ODBC驱动程序的结果?
Per bohica's suggestions, working code looks like: 根据bohica的建议,工作代码如下:
eval {
my $dbh = DBI->connect(
"dbi:ODBC:Driver={SQL Server Native Client 10.0};Server=<instance_name>;",
"Username",
"Password",
{ PrintError => 0, RaiseError => 1, AutoCommit => 1 }
);
};
Username and password were moved out of connection string and passed as separate parameters to DBI connect method. 用户名和密码从连接字符串中移出,并作为单独的参数传递给DBI connect方法。
Assuming you fix the problem Pedro mentions then, PrintError=>0 suppresses errors and you might want to look at PrintWarn as well. 假设您已解决了Pedro提到的问题,则PrintError => 0会消除错误,并且您可能还想看看PrintWarn。 The RaiseError=>1 will cause the connect to die if the connect fails and in your example the error will be in $@.
如果连接失败,则RaiseError => 1将导致连接终止,在您的示例中,错误将在$ @中出现。
connect
is a class method; connect
是一个类方法; you call it with DBI->connect
, which returns a db handle ( $dbh
in your case). 您可以使用
DBI->connect
调用它,它返回一个db句柄(在您的情况下$dbh
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.