質問

I've created an INSERT SQL query which works fine... Until I try to send a duplicate value. I'm glad the database stops the duplicate values but I don't want the system to crash. I want to know how I can check if the value I want to enter is already in the database. If it is, clear the box and produce a message box. If it isn't, carry on with the INSERT command Here is my code:

Dim strPersonID As String = cboPersonID.Text If strPersonID = "" Then Exit Sub 'Declares contents of text boxes as a string so it can be used in the 'SQL string Dim strForename As String = txtForename.Text Dim strSurname As String = txtSurname.Text Dim strDateOfBirth As String = txtDateOfBirth.Text Dim strCurrentlyWith As String = CheckIfWith() Dim strConditions As String = txtConditions.Text 'Add new record to table Dim strSQL As String = "INSERT INTO tblDetail VALUES('" & strPersonID _ & "','" & strForename & "','" & strSurname & "','" & strDateOfBirth & "'," & strCurrentlyWith & ",'" & strConditions & "')" Dim CM As New OleDbCommand(strSQL, CN)

役に立ちましたか?

解決

put your insert inside of an If not Exists statement

Dim strSQL As String = "If Not Exists (" & _
             "Select * From tblDetail "  & _
             "Where PersonId = " & strPersonID & ")" & _
    "INSERT INTO tblDetail VALUES('" & strPersonID _   
         & "','" & strForename & "','" & strSurname & 
         "','" & strDateOfBirth & "'," &
          strCurrentlyWith & ",'" & strConditions & "')" 

他のヒント

You could always catch the exception and then pop up the message based on that. A more complex alternative would be to start a transaction, run a select query to check for a duplicate, then if there are no duplicates, run your insert statement, and commit the transaction. If there are duplicates, you could commit the transaction and inform the user.

Here's a rough idea of how you'd do it with a try-catch block:

        Try
            'put your code here that could throw the exception.
        Catch ex As SqlClient.SqlException
            If (ex.Message.Contains("whatever the message is stating you have a duplicate")) Then
                MsgBox("You have a duplicate!")
            End If
        End Try
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top