2017-01-31 79 views
-1

我的vb.net代碼應該連接到我的數據庫。它直到我添加了一個查詢來檢查用戶名和密碼是否存在。添加後,用戶被拒絕訪問,同時仍然使用相同的密碼。這可能是什麼原因?代碼:運行查詢時用戶被拒絕訪問

MysqlConn = New MySqlConnection() 

    MysqlConn.ConnectionString = "server=;" _ 
    & "user id=;" _ 
    & "password=;" _ 
    & "database=" 

    Try 
     MysqlConn.Open() 
     Using cmd As New MySqlCommand 
      cmd.CommandText = "SELECT COUNT(*) From tableUser WHERE Username=" & TextBox1.Text & " AND Password=" & TextBox2.Text 
      cmd.CommandType = CommandType.Text 
      cmd.Connection = MysqlConn 
      result = cmd.ExecuteScalar 
     End Using 
     MysqlConn.Close() 
     If (result < 1) Then 
      MessageBox.Show("Please make sure you have typed valid credentials!") 
     ElseIf result = 1 Then 
      Dim form As New Form2 
      form.Show() 
      Me.Close() 
     End If 
    Catch myerror As MySqlException 
     MessageBox.Show("Connection to the database has been lost. Please try again later.") 
    Finally 
     MysqlConn.Dispose() 
    End Try 
+7

*請*使用參數化查詢**查看**。 *停止在數據庫中以純文本格式存儲密碼!*您的代碼只是乞求[Bobby Tables](http://bobby-tables.com/)來訪問。 – Siyual

+1

這裏沒有足夠的信息。準確地說,用戶在什麼時候拒絕訪問?當你運行下一個查詢?發佈確切的錯誤消息和代碼出現的位置。上面的註釋重新安全和SQL注入也是非常有效的,btw – ADyson

+1

是的,我知道關於以純文本存儲它們,這純粹是作爲一個測試:) – Matt142

回答

0

這裏有一些代碼,我只是寫它,希望它有幫助,只是改變它的需要。

Private Sub login() 
    conn = New MySqlConnection 
    con.ConnectionString = 
     "server=localhost;userid=root;password=1234;database=batabase;port=3307" 
    Dim READER As MySqlDataReader 
    If TextBox1.Text = "" Then 


     MessageBox.Show("Please enter usename ! ", "Enter username") 
     Exit Sub 

    End If 
    If TextBox2.Text = "" Then 

     MessageBox.Show("Please enter password", "Enter password") 
     Exit Sub 
    End If 


    Try 


     conn.Open() 
     Dim Query As String 
     Query = "select * from db.users where user='" & TextBox1.Text & "' and password='" & TextBox2.Text & "' " 
     COMMAND = New MySqlCommand(Query, conn) 
     READER = COMMAND.ExecuteReader 
     Dim count As Integer 

     count = 0 
     While READER.Read 
      count = count + 1 
     End While 

     If count = 1 Then 

      Form.Show() 
      Me.Hide() 

     ElseIf count > 1 Then 
      MessageBox.Show("The username is already in use!") 
     Else 
      MsgBox("Error , please try again ", MsgBoxStyle.Critical) 
     End If 




     conn.Close() 
    Catch ex As Exception 
     MessageBox.Show(ex.Message) 
    Finally 
     conn.Dispose() 
    End Try 
End Sub 

將數據庫名稱用戶名更改爲您的需要,它將工作!

只需在您的表單上添加登錄按鈕()即可! 或在您的按鈕上輸入此代碼,無需私人分站登錄()