在vb.net中保存数据库时如何避免重复条目

时间:2015-01-22 01:59:21

标签: sql-server vb.net

我有一个按钮,但它可以保存重复的条目我不知道如何正确地放置一个如果不存在的操作员请帮助..

  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

2 个答案:

答案 0 :(得分:1)

试试这个:

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()

并且不要忘记在您的数据库中将您的StudentID字段设为唯一。

答案 1 :(得分:1)

您可以使用NOT EXISTS来防止重复插入:

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

您应始终使用参数化查询来避免SQL注入攻击。

注意:请申请相应的字段类型。