我的数据库是access,用的是adoquery,在插入一条新纪录时,我想让他主键重复时报错,而不是弹出delphi的系统错误!
如何控制主键不能重复,用try……except可以吗?异常类型是什么?

解决方案 »

  1.   

    该异常的类型为EdatabaseError
    异常代码为9729;
    剩下的你应该知道怎么办了.
      

  2.   

    truexeen,真是不好意思,我基本上没有用过异常,这才想学学,我是这么写的:procedure TFormstudent.suiButton7Click(Sender: TObject);
    var sql:string;
    begin
     if strtoint(dbedit16.Field.Value)>0 then
     try
      //添加
      sql:='insert into score values('+''''+studentno+''','+''''+dbedit17.Field.Value+''','+'-1)';
      adoqueryselect.Close;
      adoqueryselect.SQL.Clear;
      adoqueryselect.SQL.Add(sql);
      adoqueryselect.ExecSQL;
      //刷新显示
      sql:='select score.cno,cname from course,score where course.cno=score.cno and score.score=-1 and sno='+''''+studentno+'''';
      adoqueryselect.Close;
      adoqueryselect.SQL.Clear;
      adoqueryselect.SQL.Add(sql);
      adoqueryselect.open;
      dbgrid2.Update;
      showmessage('成功');
     except
      on EdatabaseError do showmessage('你已选过此课')
     end;
    end;
      

  3.   


      sql:='insert into score (您的字段名!!!!!!)values('+''''+studentno+''','+''''+dbedit17.Field.Value+''','+'-1)';
      

  4.   

    MichealLee谢谢,我的插入是所有字段,所以不需要字段名,运行很正常