数据库中的一个字段被设置为主键,用VB6进行前台的开发。在没有写有关的错误检测代码之前,两次输入的记录如果主键字段相同,后一条记录将不会被记入数据库中。
请问,有没有什么办法检测到返回码或异常,提示数据库中已经有一条重复记录了。不想手工遍历,一个一个的对比。谢谢!

解决方案 »

  1.   

    Public nadorec1 As New ADODB.Recordset, nadocon1 As New ADODB.Connection
    dim txt1 as stringconstr1 = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\你的数据库.mdb;Persist Security info=false"
    nadorec1.Open "Select * from 数据表 order by 主键", nadocon1, adOpenKeyset, adLockOptimistic
    nadorec1.find "类别编码='" & txt1 & "'"
    if not nadorec1.eof then
      MsgBox "XX已存在,请重新操作!", vbInformation + vbOKOnly, "提示"
      Exit Sub
    end if
      

  2.   

    如果数据库是SQL,那么最好用存储过程来实现,可以直接在存储过程中捕获主键冲突,然后将错误消息传至前台。