抛出例外,我有当插入一个重复的值PDO不是抛出一个异常奇怪的问题。在这种情况下,我确实希望有一个错误。PHP PDO不会对重复键插入
相关的代码:
try
{
$db_conn = new PDO("mysql:host=".$config["database"]["hostname"].";charset=utf8", $config["database"]["username"], $config["database"]["password"], []);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db_conn->exec(file_get_contents("some_file_with_data.sql");
}
catch(Exception $e)
{
// PDOException extends RuntimeException extends Exception so exceptions should be catched here
// however for the duplicate key entry it will not throw an exception
}
与SQL数据的文件包含多个插入物是这样的:
INSERT INTO `a` (`b`, `c`) VALUES
(1, 1),
(2, 2),
(3, 2);
INSERT INTO `a` (`b`, `c`) VALUES
(1, 1);
在表a
字段b
被设置为作为主键。当我使用phpMyAdmin在完全相同的结构中插入完全相同的数据时,出现此错误:#1062 - Duplicate entry '65533' for key 'PRIMARY'
为什么PDO在这种情况下不会抛出错误?即使当我将错误模式设置为异常?
编辑: 这是用于特殊表
CREATE TABLE IF NOT EXISTS `a` (
`b` smallint(5) unsigned NOT NULL,
`c` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`b`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
http://stackoverflow.com/questions/11102644/pdo-exception-questions-how-to-catch-them –
我已经把它放在try/catch块中,让我更新我的代码来澄清这一点。 – Matthijs
桌子上设置的确切约束是什么? – deceze