在vb.net中添加记录并使用elseif检查记录是否存在

时间:2013-12-18 04:18:24

标签: vb.net

我是vb.net的新手..很抱歉提前。    任何人都可以帮我解决我的elseif代码行的错误。

    Dim con As SqlConnection = New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=ordering;User ID=sa;Password=123")
    Dim cmd1 As SqlCommand = New SqlCommand("Select * from Customer", con)

    Dim first1 As String
    Dim second2 As String
    first1 = "FirstName"
    second2 = "LastName"

    con.Open()
        If TextBox1.Text = "" Or TextBox2.Text = "" Then
            MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Add New Customer!")
        'this will supposedly display error message for "User Already Exist"
        ' ElseIf textbox1.text = first1 and textbox2.text = second2 Then
        '   MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
        Else
            Dim cmd As SqlCommand = New SqlCommand("Insert into [ordering].[dbo].[Customer] ([FirstName],[LastName]) values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con)
            cmd.ExecuteNonQuery()
            MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
            TextBox1.Text = ""
            TextBox2.Text = ""
            con.Close()

        End If

1 个答案:

答案 0 :(得分:9)

您需要通过执行SELECT * FROM Customer查询来实际检查用户是否已存在,但您需要添加WHERE子句,如下所示:

If TextBox1.Text = "" Or TextBox2.Text = "" Then
    MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Add New Customer!")
Else
    Dim theQuery As String = "SELECT * FROM Customer WHERE FirstName=@FirstName AND LastName=@LastName"
    Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
    cmd1.Parameters.AddWithValue("@FirstName", TextBox1.Text)
    cmd1.Parameters.AddWithValue("@LastName", TextBox2.Text)

    Using reader As SqlDataReader = cmd1.ExecuteReader()
        If reader.HasRows Then
            ' User already exists
            MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
        Else
            ' User does not exist, add them
            Dim cmd As SqlCommand = New SqlCommand("Insert into [ordering].[dbo].[Customer] ([FirstName],[LastName]) values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con)
            cmd.ExecuteNonQuery()
            MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
            TextBox1.Text = ""
            TextBox2.Text = ""
        End If
    End Using    

    con.Close()
End If

  

注意:我在SELECT *查询中添加了参数化查询的用法。您应该更喜欢参数化查询到内联SQL,因为它可以保护您的代码免受SQL注入攻击。永远不要相信用户输入的数据。