这里首先来介绍一下数据库操作的错误处理。(以MySQL为例)
使用eval{}if($@){}来完成错误处理。
先举例子
eval{
$dbh = DBI->connect($database,$db_user,$db_pswd,{RaiseError=>1,AutoCommit=>0,PrintError=>0});
# 数据库操作写在这里
};
if ($@) {
# 错误处理写在这里
# $@为错误描述
$errCode=$DBI::err; # 错误号
SWITCH:{
if ($errNumber==1044) {print("DatabaseName error!");last SWITCH;}
if ($errNumber==1045) {print("UserName or Password error!");last SWITCH;}
if ($errNumber==2003) {print("Can't connect to MySQL server! Please check out the value of DBhost,DBport and the physical connection that is from client to MySQL server.");last SWITCH;}
if ($errNumber==2013) {print("Lost connection to MySQL server!");last SWITCH;}
printLog(@_[0]);
} # 根据错误号进行提示,或者错误处理
}
注意:1 eval使用时,数据库联接的选项RaiseError=>1这样设置。
2 PrintError=>0 表示不在控制台打印错误信息。