我想知道当execute()
返回false时PDO是否会抛出异常。
<?php
$db = new PDO('mysql:host=localhost;dbname='.$dbname, $user, $pass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
$db->beginTransaction();
$query = $db->prepare('INSERT INTO threads (title,perma) VALUES ("hey", "hey")');
if(!$query->execute())
{
echo ":(";
}
}catch(Exception $e){
echo ":)";
$db->rollBack();
}
?>
是否可以看到':('?我应该手动抛出异常吗?
答案 0 :(得分:1)
如果execute()返回false,PDO会抛出异常吗?
是
您始终可以创建测试用例并亲自查看
$pdo = new PDO("mysql:host=localhost;dbname=$dbname;charset=utf8", $user, $pass);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->query("CREATE temporary TABLE executest (id int auto_increment primary key)");
$stmt = $pdo->prepare("INSERT INTO executest VALUES (?)");
$stmt->execute([1]);
$stmt->execute([1]);