2014-02-28 102 views
0

在找到解決方案之前一直清醒。有沒有辦法在插入值之前檢查我的Access數據庫上的重複內容,並向我發送已有記錄的消息。這裏是我的代碼,我不知道在哪裏以及如何檢查它在插入之前在Access數據庫中檢查重複

Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click 

      If txtCat.Text = "" Then 
       MsgBox("Please Complete the Information Needed") 
       txtCat.Focus() 


      Else 
       If MsgBox("Are you sure you want to Add Category?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "WARNING") = MsgBoxResult.Yes Then 

        Dim DBC As New OleDbCommand 
        With DBC 
         .Connection = conn 
         .CommandText = "INSERT INTO tbl_category(Category) VALUES('" & txtCat.Text & "')" 
         .ExecuteNonQuery() 
        End With 
        MsgBox("Category Added!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "SUCCESS") 

        Call CatList() 

        txtCat.Text = "" 
        txtCat.Enabled = False 
        btnSave.Enabled = False 

        Call CatCombo() 


       End If 
      End If 

     End Sub 

這是我第一次來檢查重複的,這就是爲什麼我不知道該怎麼

+1

如果您不想在數據庫中使用重複項,請設置唯一索引,以免數據庫出現重複項。 – Steve

回答

0

像這樣的工作:

"INSERT INTO tbl_category(Category) VALUES('" & txtCat.Text & "') WHERE NOT EXISTS (Select '8' from tbl_category where Category = + " & txtCat.Text & + " 

當然,這並不是最好的做法。這種格式容易受到SQL注入的影響。

+0

它給我一個錯誤,「查詢輸入必須包含至少一個表或查詢。」 – mobinuya

+0

看看這個鏈接:http://www.utteraccess.com/forum/exists-access-t1914818.html這裏討論設置一個將返回一行的虛擬表,並允許你解決這個異常。 – briskovich

相關問題