直接使用try...catch....結(jié)構(gòu)。比如:
成都創(chuàng)新互聯(lián)的客戶來(lái)自各行各業(yè),為了共同目標(biāo),我們?cè)诠ぷ魃厦芮信浜?,從?chuàng)業(yè)型小企業(yè)到企事業(yè)單位,感謝他們對(duì)我們的要求,感謝他們從不同領(lǐng)域給我們帶來(lái)的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶帶來(lái)驚喜。專業(yè)領(lǐng)域包括成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作、電商網(wǎng)站開(kāi)發(fā)、微信營(yíng)銷(xiāo)、系統(tǒng)平臺(tái)開(kāi)發(fā)。
try
{
DB::query("SELECT?count(*)?FROM?pre_111?WHERE?fid?=?$fid";
}
catch(exception?$ex)
{
echo($ex-getMessage());
}
從Mysql 5.5 開(kāi)始為我們提供了SIGNAL函數(shù)來(lái)實(shí)現(xiàn)這個(gè)功能。
[sql] view plain copy
CREATE TRIGGER `tg_order_create` AFTER INSERT ON `tp_order` FOR EACH ROW BEGIN
DECLARE msg varchar(200);
/*凍結(jié)金額*/
IF 2=NEW.condition THEN
UPDATE `tp_user` SET `frozen_amount`=`frozen_amount`+NEW.amount WHERE `id`=NEW.uid AND `amount`-`frozen_amount` NEW.amount;
/*如果余額不足,產(chǎn)生一個(gè)錯(cuò)誤*/
IF ROW_COUNT() 1 THEN
set msg = "用戶余額不足以完成支付.";
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = msg;
END IF;
/*扣除金額*/
ELSEIF 3=NEW.condition THEN
UPDATE `tp_user` SET `amount`=`amount`-NEW.amount WHERE `id`=NEW.uid AND `amount`-`frozen_amount` NEW.amount;
/*如果余額不足,產(chǎn)生一個(gè)錯(cuò)誤*/
IF ROW_COUNT() 1 THEN
set msg = "用戶余額不足以完成支付.";
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = msg;
END IF;
END IF;
END;
這里這條觸發(fā)器的功能是庫(kù)存操作,當(dāng)庫(kù)存足夠的時(shí)候 減少庫(kù)存,否則 拋出一個(gè)異常并報(bào)告商品庫(kù)存不足:
[sql] view plain copy
CREATE TRIGGER `TG_order_detail_dec_stock` BEFORE INSERT ON `tp_order_detail` FOR EACH ROW BEGIN
DECLARE msg VARCHAR(200);
UPDATE `tp_stock` SET `num`=`num`-NEW.num WHERE `goods_id`=NEW.goods_id AND `mid`=NEW.mid AND `num`=NEW.num;
IF ROW_COUNT() 1 THEN
SELECT CONCAT(`name`, ' 庫(kù)存不足.') INTO msg FROM `tp_goods` WHERE `id`=NEW.goods_id;
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = msg;
END IF;
END;
在PHP端的處理(注:使用ThinkPHP框架):
[php] view plain copy
//前面省略若干行....
try {
if (false === ($order_pk = $tbl_order-add($order))) {
$tbl-rollback();
echo json_encode(array('success' = -1, 'message' = "創(chuàng)建訂單失敗!."), JSON_UNESCAPED_UNICODE);
return;
}
}catch (\PDOException $e){
$errInfo=$e-errorInfo[2];
$tbl-rollback();
echo json_encode(array('success' = -1, 'message' = "創(chuàng)建訂單失敗!,{$errInfo}"), JSON_UNESCAPED_UNICODE);
return;
}
//后面省略若干行....
user表不存在;而且一般情況下user屬于關(guān)鍵字,不應(yīng)該把user當(dāng)表名直接用
分享名稱:mysql怎么拋出異常,mysql存儲(chǔ)過(guò)程主動(dòng)拋出異常
鏈接URL:http://jinyejixie.com/article4/dsseeie.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、ChatGPT、自適應(yīng)網(wǎng)站、移動(dòng)網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、App設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)