所以我正忙着搬到PDO(是的,我仍然是那种老式的mysql驱动程序),我之前从未使用过异常。我的代码基于我迄今所理解的内容。我将需要它的应用程序将创建3个单独的数据库连接,其中2个将是mysql和1个mssql(因此类型为if else)。
问题在于,即使我提供了错误的连接值,它仍会处理并继续执行脚本,并完全跳过“catch”,就好像没有错误一样。我知道基础应该是:
try {
if("condition" != "conditions") {
throw new Exception("Oops I did it again");
}
catch(Exceptions as e) {
echo $e->getMessage();
}
我也明白,PDO会通过例外,所以我不必抛出,但它只是没有成功,请帮助,并对我对这个概念的误解更多的疏忽:
// connect(): Connect to a database (MySQL):
private function connect($cred) {
$type = $cred['type'];
if($type == "mysql") {
try {
$handler = new PDO("mysql:host".$cred['credentials']['server'].";dbname=".$cred['credentials']['database'].", ".$cred['credentials']['username'].",".$cred['credentials']['password']);
if($cred['errors'] == 'exception') {
$handler->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} elseif($cred['errors'] == 'warning') {
$handler->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
} else {
$handler->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
}
}
catch(PDOException $e) {
$this->informer("FATAL","An error has occured trying to connect to the connection (".$cred['name'].") -".$e->getMessage());
return false;
}
return $handler;
}
}
答案 0 :(得分:0)
发现了这个问题,这是我PDO异议创建中的语法问题,我有:
$handler = new PDO("mysql:host".$cred['credentials']['server'].";dbname=".$cred['credentials']['database'].", ".$cred['credentials']['username'].",".$cred['credentials']['password']);
应该是:
$handler = new PDO("mysql:host=".$cred['credentials']['server'].";dbname=".$cred['credentials']['database'].", ".$cred['credentials']['username'].",".$cred['credentials']['password']);
答案 1 :(得分:0)
我只是在这里猜测,但是要从构造函数中接收PDO异常,您可能必须在new
调用中传递属性:
new PDO($dsn, $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
<强>更新强>
刚测试过,但即使没有传递属性也会引发异常。