2017-02-04 3 views
0

Я создал код для отображения правильного сообщения, если имя пользователя и пароль вставлены правильно. Имя пользователя и пароли пользователей извлекаются из таблицы базы данных. Но я всегда получаю сообщение о неправильном имени пользователя и пароле. Я не знаю почему. Вот мой кодподключение базы данных Mysql и визуального базового

Private Sub Button2_Click (ByVal отправитель Как System.Object, ByVal е Как System.EventArgs) Ручки btnLogIn.Click MySqlConn = Новый MySqlConnection

MySqlConn.ConnectionString = "server=localhost;userid=root;password=12345;database=environment" 

    Dim READER As MySqlDataReader 



    Try 
     MySqlConn.Open() 
     Dim Query As String 
     Query = "select * from environment.customers where customer_name='" & txtUser.Text & "'and customer_detail='" & txtPass.Text & " '" 

     COMMAND = New MySqlCommand(Query, MySqlConn) 
     READER = COMMAND.ExecuteReader 

     Dim count As Integer 
     count = 0 
     While READER.Read 
      count = count + 1 

     End While 

     If count = 1 Then 
      MessageBox.Show("username and password are correct") 
     ElseIf count > 1 Then 
      MessageBox.Show("username and password are duplicate") 
     Else 
      MessageBox.Show("username and password are incorrect") 

     End If 



     MySqlConn.Close() 

    Catch ex As MySqlException 
     MessageBox.Show(ex.Message) 

    Finally 
     MySqlConn.Dispose() 


    End Try 
End Sub 

End Class

+0

Короткий ответ заключается в том, что счетчик всегда будет как минимум 1. Цикл while будет выполняться хотя бы один раз независимо от результата. Во-вторых, вы должны не хранить ваши пароли как обычный текст. – MaCron

ответ

0

Попробуйте это в вашем коде.

#Region "Members" 
    Protected WithEvents lblMessage As System.Web.UI.WebControls.Label 
    #End Region 

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click MySqlConn = New MySqlConnection 
If Not IsPostBack Then 
    If Not IsNothing(txtUser.text) Then 'Replace this field with your own field name. 
     If Not IsNothing(txtPass.text) Then 'Replace this field with your own field name. 
      Login() 'If both login form is not empty, execute login function 
     Else 
      LabelMessage.Text("Please enter your password.") 'If password field is empty 
      LabelMessage.Visible = True 
      Exit Sub 
     EndIf 
    ElseIf IsNothing(txtUser.text) AND IsNothing(txtPass.text)Then 
     LabelMessage.Text("Please enter your username and password.") 'If both field are empty 
     LabelMessage.Visible = True 
     Exit Sub 
    Else 
     LabelMessage.Text("Please enter your username.") 'If username field are empty 
     LabelMessage.Visible = True 
     Exit Sub 
    EndIf 
EndIf 
End Sub 

Private Sub Login() 

Dim conn As New SqlConnection 
Dim command As New SqlCommand 
Dim Password As String 
Dim Password2 As String 
Dim Username As String 

Try 
    conn.ConnectionString = "server=localhost;userid=root;password=12345;database=environment" 'Your SQL Database credentials 
    conn.Open() 'Open the connection 
    command.Connection = con 

    command.CommandText = "SELECT customer_name, customer_details FROM environment.customers WHERE (customer_name = '" & txtUser.text & "') AND (Password='" & txtPass.text & "')" 

    Dim lrd As SqlDataReader = command.ExecuteReader() 
    If lrd.HasRows Then 
     While lrd.Read() 
      Username = lrd("customer_name").ToString() 
      Password = lrt("Password").ToString() 
      Password2 = txtPass.txt() 


      If Password = Password2 and Username = txtUser.text Then 
       MessageBox.Show("Logged in successfully as " & Username, "", MessageBoxButtons.OK, MessageBoxIcon.Information) 
       frmMain.Show() 
       Me.Hide() 
       Response.Redirect("~/Index.aspx") 'Redirect to your homepage. 

       'Clear the login field 
       txtPassword.Text = "" 
       txtUsername.Text = "" 

      End If 

     End While 

    Else 
     MessageBox.Show("Username and Password does not match.", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) 

     'Clear the login Field 
     txtPassword.Text = "" 
     txtUsername.Text = "" 

    EndIf 

Catch ex As Exception 
    Messagebox.Show("Error while connecting to SQL Server." & ex.Message) 
Finally 
    con.Close() 'After finish execute anything, force close the connection. (Whether succeed or not.) 
End Sub