请教各位,向Oracle数据库插入记录时,如何捕捉主键冲突的异常(100分)

  • 主题发起人 主题发起人 xda
  • 开始时间 开始时间
X

xda

Unregistered / Unconfirmed
GUEST, unregistred user!
如题,请各位指教
 
oracle主键错误号为:ORA-00001 <br>上边不是有错误码吗,在OnPostErr里写吧,可以根据返回的错误代码
 
请问luoyanqing119,如何在Try Except end中捕捉这一异常呢?
 
try <br>… <br>… <br>except <br>&nbsp; &nbsp; &nbsp; on &nbsp; e &nbsp; : &nbsp; EOraError &nbsp; do <br>&nbsp; &nbsp; &nbsp; &nbsp; begin <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if &nbsp; e.ErrorCode &nbsp; = &nbsp; 00001 &nbsp; then <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ErrorInfo &nbsp; := &nbsp; '存在此部门的关连记录,禁止删除! ' <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ErrorInfo &nbsp; := &nbsp; '数据库操作错误 '; <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Result &nbsp; := &nbsp; False; <br>&nbsp; &nbsp; &nbsp; &nbsp; end; <br>end; <br><br>ErrorCode &nbsp; := &nbsp; 1代表主键重复,针对插入记录的函数使用(同上) <br>代码大概就这样,你去改一下,另外,主键冲突的错误码不知道对不对,查一下就可以了。
 
也可以用最简洁的。<br>try <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DM.query1.Close; <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DM.query1.SQL.clear; <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DM.query1.SQL.Add(sql); <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DM.query1.ExecSQL; <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result:=true; <br>&nbsp; &nbsp; except <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; On &nbsp; E:Exception &nbsp; do <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; begin <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ShowMessage(E.message); <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result:=false; <br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; end; <br>BDE,ADO均通用<br><br>&nbsp; &nbsp; end;
 
谢谢luoyanqing119,我也找到了您说的代码,就是错误码是2292,但我查不到Oracle主键重复的准确的错误代码,请问什么地方可以查到吗?
 
或者这样:<br>except On E: Exception do <br>begin <br>&nbsp; if Copy(E.Message, 1, 9) = 'ORA-00001' then <br>&nbsp; ...; <br>end;<br>...
 
你自己到PL SQL中去插一条记录看看报错号就可以了
 
谢谢各位的指教!我的需求是先将数据保存在本地数据库,然后一条一条的定期上传,如果上传成功或主键冲突,则从本地数据库中删除,否则等待下次上传。我在应用服务器中采用如下代码,经少量数据调试可以达到上述要求,但这样做不知是否可靠,请各位发表看法。<br>Var<br>&nbsp; B:Byte; &nbsp;{0-上传成功,1-主键冲突,2-上传失败}<br>begin<br>&nbsp; ...... &nbsp;{生成插入数据的SQL语句}<br>&nbsp; &nbsp; Try<br>&nbsp; &nbsp; SQLQuery1.ExecSQL(False);<br>&nbsp; &nbsp; B:=0;<br>&nbsp; Except<br>&nbsp; &nbsp; On E:EDatabaseError Do<br>&nbsp; &nbsp; &nbsp; If Pos('ORA-00001',E.Message)&lt;&gt;0<br>&nbsp; &nbsp; &nbsp; &nbsp; Then B:=1<br>&nbsp; &nbsp; &nbsp; &nbsp; Else B:=2;<br>&nbsp; end;<br>&nbsp; ...... &nbsp;{将B返回到客户端}<br>end;
 
多人接受答案了。
 

Similar threads

后退
顶部