-1

I have a button but it can save duplicate entries i don't know how to correctly put a if not exist operator pls help..

  cmd = New SqlCommand("INSERT INTO Students(Familyname,Firstname,Middlename,StudentID)VALUES('" & txtname.Text & "','" & txtfname.Text & "','" & txtmname.Text & "','" & txtid.Text & "')", cn)

    cn.Open()
    i = cmd.ExecuteNonQuery
    cn.Close()

    If txtname.Text <> "" Then
    ElseIf i > 0 Then
        MsgBox("Save Sucessfully!", MessageBoxIcon.Information, "Success")
        showrecord()
        clear()
    Else
        MsgBox("Save Failed!", MessageBoxIcon.Error, "Error")
    End If
Men8 Burger
  • 3
  • 1
  • 2
  • 7

2 Answers2

2

You can use NOT EXISTS to prevent duplicate insert:

Dim sql = "INSERT INTO Students(Familyname, Firstname, Middlename, StudentID) " & _
            "VALUES(@FamilyName, @Firstname, @Middlename, @StudentID)" & _
            "WHERE NOT EXISTS(SELECT 1 FROM Students WHERE StudentId = @StudentID)"

        Using cn As New SqlConnection("Your connection string here")
            Dim cmd As SqlCommand = New SqlCommand(sql, cn)

            cmd.Parameters.Add("@FamilyName", SqlDbType.VarChar, 50).Value = txtname.Text
            cmd.Parameters.Add("@Firstname", SqlDbType.VarChar, 50).Value = txtfname.Text
            cmd.Parameters.Add("@Middlename", SqlDbType.VarChar, 50).Value = txtmname.Text
            cmd.Parameters.Add("@StudentID", SqlDbType.VarChar, 50).Value = txtid.Text

            Dim i = cmd.ExecuteNonQuery
        End Using

You should always use parameterized queries to avoid SQL Injection attacks.

NOTE: Please apply appropriate field types.

Felix Pamittan
  • 31,544
  • 7
  • 41
  • 67
1

Try this one :

cn.Open()
Dim intReturn as integer
Dim strSql as string = "Select * from Students where StudentID = @StudentID"

sqlcmd = new sqlcommand(strSql, cn)
With sqlcmd.parameters
  .addwithvalue("@StudentID", ctype(txtid.text,string)
End with

intReturn = sqlcmd.ExecuteScalar

If(intReturn > 0)
    cmd = New SqlCommand("INSERT INTO Students(Familyname,Firstname,Middlename,StudentID)VALUES('" & txtname.Text & "','" & txtfname.Text & "','" & txtmname.Text & "','" & txtid.Text & "')", cn)

    i = cmd.ExecuteNonQuery

    If txtname.Text <> "" Then
    ElseIf i > 0 Then
        MsgBox("Save Sucessfully!", MessageBoxIcon.Information, "Success")
        showrecord()
        clear()
    Else
        MsgBox("Save Failed!", MessageBoxIcon.Error, "Error")
    End If
Else
    MsgBox("Student Already Exist", MessageBoxIcon.Error, "Error")
End If
cn.Close()

And don't forget to make your StudentID field as Unique in your database.

Jun Rikson
  • 1,964
  • 1
  • 22
  • 43