Self learning on vb.net

64 views Asked by At

Currently I'm trying to understand and learn new code commands for vb.net. i have came across three codes while researching which is

"SELECT staff_id,pass_word FROM userlogin WHERE staff_id = @staff_id AND pass_word = @pass_word")

Second code:

Dim uName As New OleDbParameter("@staff_id", SqlDbType.VarChar)

Third and last:

uName.Value = txtstaffid.Text
myCommand.Parameters.Add(uName)

What are the uses of @pass_word code when you have already typed the pass_word column, Oledbparameter, and Parameters.Add?

1

There are 1 answers

1
Mary On

The following code shows a bit more complete picture of what the code is doing. The Using...End Using blocks ensure that your objects are closed and disposed even if there are errors. Of course, in a real application, passwords would never be stored as plain text (too easy to hack). They would be salted and hashed but that is for another day.

Private Sub CheckPassword()
        'This line assigns a Transact SQL command to a string variable.
        'It will return a record with 2 columns. The @staff_id and @pass_word are parameter placeholders.
        'The use of parameters limits the possibilit of SQL injection with malicious input be the user
        'typing in the text box.
        Dim strSQL = "SELECT staff_id,pass_word FROM userlogin WHERE staff_id = @staff_id AND pass_word = @pass_word;"
        Using cn As New SqlConnection("Your connection string")
            'Pass the command string and the connection to the constructor of the command.
            Using cmd As New SqlCommand(strSQL, cn)
                'It is unneccessary to create a command variable.
                'The .Add method of the commands Parameters collection will create a parameter.
                cmd.Parameters.Add("@staff_id", SqlDbType.VarChar).Value = txtstaffid.Text
                cmd.Parameters.Add("@pass_word", SqlDbType.VarChar).Value = txtPassword.Text
                cn.Open()
                Using dr As SqlDataReader = cmd.ExecuteReader
                    'All we really need to know is whether we returned a row.
                    If dr.HasRows Then
                        MessageBox.Show("Login Successful")
                    Else
                        MessageBox.Show("Login Failed")
                    End If
                End Using
            End Using
        End Using
End Sub