VB.NET数据库在提交前检查是否重复

时间:2013-11-13 18:24:40

标签: asp.net sql vb.net

我被要求更新遗留的VB.net应用程序,虽然我已经完成了部分工作,但是在将其添加到数据库表之前,我很难实现验证检查以确保行不存在。以下是我的代码。我以为我有它工作,但它只是通过我的其他声明。我想将下拉列表中的两个值传递给参数,然后检查指定列中是否存在包含这些参数的行。

Private Sub joinValidation(ByVal source As Object, ByVal e As EventArgs)
    Using connection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("System_Configuration").ConnectionString)
        Using cmd As SqlClient.SqlCommand = connection.CreateCommand()

            cmd.CommandText = "SELECT 1 FROM Join_Connection WHERE Alias1ID = @Alias1Check AND Alias2ID = @Alias2Check"
            cmd.Parameters.AddWithValue("@Alias1Check", Datasource1.SelectedValue)
            cmd.Parameters.AddWithValue("@Alias2Check", Datasource2.SelectedValue)
            cmd.Connection.Open()
            Dim exists As String = cmd.ExecuteScalar().ToString()
            If exists = "1" Then
                Response.Write("<script language='javascript'>alert('This Alias already exists in the Alias table.');</script>")
                cmd.Connection.Close()
            ElseIf exists = "0" Then
                addJoin()
                joinResetPage()
            End If
        End Using
    End Using
End Sub

我对VB.NET不是很熟悉所以任何帮助或建议都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

尝试以下代码可能会对您有所帮助:

 Private Sub joinValidation(ByVal source As Object, ByVal e As EventArgs)
        Using connection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("System_Configuration").ConnectionString)
            Using cmd As SqlClient.SqlCommand = connection.CreateCommand()

                cmd.CommandText = "SELECT count(1) FROM Join_Connection WHERE Alias1ID = @Alias1Check AND Alias2ID = @Alias2Check"
                cmd.Parameters.AddWithValue("@Alias1Check", Datasource1.SelectedValue)
                cmd.Parameters.AddWithValue("@Alias2Check", Datasource2.SelectedValue)
                cmd.Connection.Open()
                Dim exists As Integer = 0
                Integer.TryParse(Convert.ToString(cmd.ExecuteScalar()), exists)
                If exists > 0 Then
                    Response.Write("<script language='javascript'>alert('This Alias already exists in the Alias table.');</script>")
                    cmd.Connection.Close()
                Else
                    addJoin()
                    joinResetPage()
                End If
            End Using
        End Using
    End Sub