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

Sam*_*ong 2 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
Run Code Online (Sandbox Code Playgroud)

Kar*_*son 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
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢卡尔爵士……与我在谷歌搜索的其他代码相比,您提供了很大的帮助,并且您的代码易于理解。=) (2认同)