2015-11-06 54 views
-1

我登錄頁面我的代碼VB.NET代碼:VB.NET SQL Server的SELECT COUNT(*) - 的ExecuteNonQuery:Connection屬性尚未初始化

Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click 

    Try 
     If UsernameTextBox.Text = "" Then 
      MsgBox("Insert your username.") 
      UsernameTextBox.Focus() 
      Return 
     ElseIf PasswordTextBox.Text = "" Then 
      MsgBox("Insert your Passwprd.") 
      PasswordTextBox.Focus() 
      Return 
     Else 
      Dim count As Integer 
      Using con As New OleDbConnection("Provider=SQLOLEDB;Data Source=JUNIOR-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=ShopHereNow") 
       con.Open() 
       Dim command = New OleDbCommand("Select count(*) from Employees where FirstName = '" & UsernameTextBox.Text & "' and [Password] = '" & PasswordTextBox.Text & "'") 
       count = command.ExecuteNonQuery() 
       con.Close() 
       If count > 0 Then 
        MsgBox("Welcome " & UsernameLabel.Text & "!") 
        Me.Hide() 
        Home.Show() 
       Else 
        MessageBox.Show("Invalid combination. Try again...") 
        Cancel.PerformClick() 
        Return 
       End If 
      End Using 
     End If 
    Catch ex As Exception 
     MessageBox.Show(ex.Message, "ERROR5", MessageBoxButtons.OK, MessageBoxIcon.Error) 
    End Try 
End Sub 

在執行此代碼我得到錯誤閱讀:ExecuteNonQuery: Connection property has not been initialized

請幫助,我可以在哪裏編碼錯誤?

+1

在調用查詢之前,您需要將命令鏈接到您的連接,例如'command.Connection = con'。 – TZHX

回答

0

您的代碼有一些錯誤,

  1. 使用Parameterized Queries

    Dim command = New OleDbCommand("Select count(*) from Employees where FirstName [email protected] and Password = @Password") 
    command.Parameters.AddWithValue("@FirstName", UsernameTextBox.Text) 
    command.Parameters.AddWithValue("@Password", PasswordTextBox.Text) 
    

這是爲了避免SQL Injection Attack AKA For Security

  • 提到的錯誤abov e是因爲你沒有指定你的命令的連接,改變你的Dim command = New OleDbCommand("Select count(*) from Employees where FirstName [email protected] and Password = @Password")Dim command = New OleDbCommand("Select count(*) from Employees where FirstName [email protected] and Password = @Password", **con**)

  • MsgBox()是一種過時的方法,使用MessegeBox.Show()代替。

  • 請勿使用類別Exception。而是指定特定的異常類型。在這裏,您可能需要SQLException

  • +0

    在VS中有一個警告MsgBox()是不推薦使用的方法嗎?我不記得它是一個廢棄的方法。我只知道MessageBox.Show()更受歡迎,因爲您可以輕鬆地在C#中使用它。如果您導入Microsoft.VisualBasic命名空間,MsgBox()僅在C#中可用。 VB項目默認導入這個命名空間。 – Han

    +0

    非常感謝我已經完成了您提到的更改並解決了錯誤。但是,如何在上面的代碼中獲得變量「count」的值? –

    +0

    @ KeithJnrP.Mthembu:不客氣。但我不明白。現在有什麼問題?程序應該正常工作。 – Mahadev

    相關問題