捕获“INSERT”的异常关于重复密钥更新” ZF 中的解决方法
ZF 1.9.5
此处。有人建议在使用 Zend_Db_Table 时捕获异常以模拟ON DUPLICATE KEY UPDATE
。
目前,我收到
SQLSTATE[23000]: Integrityconstraint Violation: 1062 Duplicateentry 'i7dd30253497cfc0539d7c5830a926f7d' for key 'ukey'
..使用
$orderRow = $this->createRow();
$orderRow->ukey = $ukey;
$orderRow->save();
时,我想用 try 来捕获那个 bug /捕获
。出现异常时更新
,否则插入
。
但我不知道该抓什么。 Zend_Db_Exception
? PDOException
? Zend_Db_Adapter_Exception
?我已经尝试了几个,但我认为我没有得到它。
稍后编辑。 这对我有用:
try {
$orderRow = $this->createRow();
$orderRow->ukey = $ukey;
$orderRow->$stepCol = time();
$orderRow->save();
} catch (Zend_Db_Statement_Exception $e) {
// on UNIQUE error, update
if ($e->getCode() == 23000) {
$orderRow = $this->fetchRow($this->select()->where('ukey = ?', $ukey));
$orderRow->$stepCol = time();
$orderRow->save();
}
}
ZF 1.9.5
here. Someone suggested catching exceptions to emulate ON DUPLICATE KEY UPDATE
when using Zend_Db_Table.
Currently, I'm getting
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'i7dd30253497cfc0539d7c5830a926f7d' for key 'ukey'
..when using
$orderRow = $this->createRow();
$orderRow->ukey = $ukey;
$orderRow->save();
So, I want to catch that bugger with try / catch
. On exception update
, else insert
.
But I don't know what to catch. Zend_Db_Exception
? PDOException
? Zend_Db_Adapter_Exception
? I've tried several, but I don't think I got it.
Later edit.
This worked for me:
try {
$orderRow = $this->createRow();
$orderRow->ukey = $ukey;
$orderRow->$stepCol = time();
$orderRow->save();
} catch (Zend_Db_Statement_Exception $e) {
// on UNIQUE error, update
if ($e->getCode() == 23000) {
$orderRow = $this->fetchRow($this->select()->where('ukey = ?', $ukey));
$orderRow->$stepCol = time();
$orderRow->save();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需看看抛出的异常是这样的:
这应该告诉您需要捕获哪种异常,因为“Exception”将捕获每种类型的异常,无论是 ZF 异常还是 PDO 异常还是完全不同的异常
Just look what exception is getting thrown like this:
That should tell you what kind of exception you need to catch because "Exception" will catch every type of exception, be it a ZF exception or a PDO exception or something completely different
它将抛出一个
Zend_Db_Statement_Exception
。关于找出抛出的异常,您可以查看edorian的答案。
It will throw a
Zend_Db_Statement_Exception
.Regarding finding out what Exception is thrown, you could take a look at edorian's answer.