Adding records in vb.net and Checking if records exist using elseif

前端 未结 1 652
生来不讨喜
生来不讨喜 2021-01-15 19:14

I\'m new to vb.net.. so sorry in advance. can anyone help me what\'s wrong with my elseif line of code.

    Dim con As SqlConnection = New SqlConnection(\         


        
相关标签:
1条回答
  • 2021-01-15 19:50

    You need to actually check to see if the user already exists by executing the SELECT * FROM Customer query, but you need to add the WHERE clause, like this:

    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
    

    Note: I added the usage of a parameterized query in the SELECT * query. You should prefer parameterized queries to in-line SQL because it will protect your code from SQL Injection attacks. Never trust the data typed in by the user.

    0 讨论(0)
提交回复
热议问题