2014-05-09 73 views
-1
Dim nm As String 
Dim pass As String 
nm = TextBox1.Text 
pass = TextBox2.Text 

Try 
    cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Pavilion\Documents\Visual Studio 2010\Projects\WindowsApplication5\Ent.accdb" 
    cn.Open() 
    Dim sql As String 
    sql = "SELECT * FROM user WHERE UName='" & nm & "'AND Pwd='" & pass & "'" 
    cmd = New OleDbCommand(sql, cn) 
    dr = cmd.ExecuteReader 
    While (dr.Read()) 
     If ((nm.Equals(dr(0))) And pass.Equals(dr(1))) Then 
      MessageBox.Show("Login Sucessful") 
     End If 
    End While 
Catch ex As Exception 
    MsgBox("Login Failed :" & ex.Message) 
End Try 

此代碼是給下面的錯誤syntax error in FROM clause語法錯誤在vb.net

回答

0
Try 

      cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Pavilion\Documents\Visual Studio 2010\Projects\WindowsApplication5\Ent.accdb" 
      cn.Open() 
      Dim sql As String 
      sql = "SELECT * FROM user WHERE UName='" + nm + "'AND Pwd='" + pass + "'" 
      cmd = New OleDbCommand(sql, cn) 
      dr = cmd.ExecuteReader 
      While (dr.Read()) 
       If ((nm.Equals(dr(0))) And pass.Equals(dr(1))) Then 
        MessageBox.Show("Login Sucessful") 
       End If 
      End While 
     Catch ex As Exception 
      MsgBox("Login Failed :" & ex.Message) 
     End Try 
+0

仍然無法工作 – Priyanshu

+0

這段代碼與OP的發佈代碼有什麼不同?除了移動try塊的開始,我看不到任何區別...... – Tim

+0

你的編輯**仍然**不回答這個問題 - 它是OP在問題中張貼的**完全相同的代碼** !如果你要回答一個問題,然後回答它 - 並在代碼中發佈解釋*幾乎總是有幫助的。 – Tim

1

如果您發佈的代碼是複製和粘貼,你缺少的用戶名之間的空間, AND關鍵字。

你代碼:

"SELECT * FROM user WHERE UName='" & nm & "'AND Pwd='" & pass & "'" 

應該是:

"SELECT * FROM user WHERE UName='" & nm & "' AND Pwd='" & pass & "'" 

但是你應該使用參數化查詢,以避免SQL注入攻擊的可能性。事情是這樣的:

sql = "SELECT * FROM user WHERE [email protected] AND [email protected]" 
cmd = New OleDbCommand(sql, cn) 
cmd.Parameters.AddWithValue("@nm", TextBox1.Text) 
cmd.Parameters.AddWithValue("@pass", TextBox2.Text) 
cmd.CommandType = CommandType.Text 
dr = cmd.ExecuteReader 
1

@Tim是正確的,但我想你可能也有問題,你的SQL作爲user是一個保留字。如果我在SQL Server中執行

SELECT * FROM user WHERE UName='fred' AND Pwd='123' 

我得到告訴Incorrect syntax near the keyword 'user'.

您可以通過將[]周圍的表名克服這一點,即

Select * FROM [user] WHERE UName='fred' AND Pwd='123' 
+0

好點 - 雖然OP使用OleDb,但它可能不是SQL Server。然而使用'[]'不應該傷害任何東西;比對不起更安全。 – Tim

+0

連接字符串表示Access,而用戶也是一個關鍵字。 – DeanOC