2014-08-29 28 views
1

有人可以幫我解決以下問題。使用MySQL數據庫的VB.NET登錄表格

我創建了一個名爲dbhr的數據庫和一個名爲user的表,其中有兩個字段'username'和'password'具有VARCHAR數據類型。 我有兩個文本框(tbxUsername,tbxPassword)和一個確定按鈕的登錄表單。我已連接我的數據庫以驗證用戶名和密碼。但它總是給我錯誤的密碼信息。我不知道我錯在哪裏。 請幫忙。

我使用MySQL Workbench 6.1

在此先感謝。

這裏是VB.NET登錄按鈕代碼。

Imports MySql.Data.MySqlClient 

Public Class Login 

    Dim mydbcon As MySqlConnection 
    Dim COMMAND As MySqlCommand 

    ' TODO: Insert code to perform custom authentication using the provided username and password 
    ' (See http://go.microsoft.com/fwlink/?LinkId=35339). 
    ' The custom principal can then be attached to the current thread's principal as follows: 
    '  My.User.CurrentPrincipal = CustomPrincipal 
    ' where CustomPrincipal is the IPrincipal implementation used to perform authentication. 
    ' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object 
    ' such as the username, display name, etc. 

    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click 
     mydbcon = New MySqlConnection 
     mydbcon.ConnectionString = "server=localhost;userid=root;password=rootword;database=hrdb" 
     Dim reader As MySqlDataReader 

     Try 
      mydbcon.Open() 
      Dim Query As String 
      Query = "select * from user where username= ' " & tbxUsername.Text & "' and password= ' " & tbxPassword.Text & "' " 
      COMMAND = New MySqlCommand(Query, mydbcon) 
      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 wrong") 
      End If 
      mydbcon.Close() 
     Catch ex As MySqlException 
      MessageBox.Show(ex.Message) 
     Finally 
      mydbcon.Dispose() 
     End Try 

    End Sub 

請點擊以下鏈接查看數據庫表記錄和數據類型。

點擊here

+0

爲什麼你不把你的按鈕代碼放在這篇文章中,而不是提供一個鏈接到一些下載網站? – Mych 2014-08-29 14:25:49

+0

添加了按鈕代碼。我也必須提供數據庫設置,這就是爲什麼我附上截圖。 – user3765415 2014-08-29 14:35:08

+0

好的......現在你總是得到什麼信息?順便說一句,你看到的東西存儲密碼未加密的是你的意圖嗎? – Mych 2014-08-29 14:40:14

回答

0

你有一些額外的空格線

Query = "select * from user where username= ' " & tbxUsername.Text & "' and password= ' " & tbxPassword.Text & "' " 

,我會改變

Query = String.Format("SELECT * FROM user WHERE username = '{0}' AND password = '{1}'", Me.tbxUsername.Text.Trim(), Me.tbxPassword.Text.Trim()) 

我會用String.Format(),以使其更清晰,更少的機會忽略那些多餘的空格。

+0

乾杯。你能告訴我哪裏留下了額外的空間嗎?如果我刪除多餘的空格,那麼在我的格式上使用你的格式會有什麼不利嗎?我只想知道我的編碼是否更糟。 :) – user3765415 2014-08-29 15:23:30

+0

...'和'之間的用戶名='「',同樣在密碼上。 – djv 2014-08-29 15:31:50

+0

'username ='{0}''中的額外空間與'where username ='「'相比是非常明顯的。在這種簡單的情況下,這是一個優先選擇的問題,儘管我認爲清晰度比使用String.Format在功能上,它們是一樣的 – djv 2014-08-29 15:34:35