2015-11-22 44 views
-2

我想創建並保存在我的數據庫中的配置文件詳細信息,但我得到一個錯誤,說:「ExecuteReader需要一個開放和可用的連接。關閉。任何幫助,將不勝感激。這是我的代碼。ExecuteReader需要一個開放和可用的連接VB.NET

Imports System.Data.OleDb 

Public Class Profile 

    Public profileConnection As New OleDbConnection 
    Public profileCommand As New OleDbCommand 
    Dim anewProfile As New PlayerProfile() 


Private Sub CreateProfileButton_Click(sender As Object, e As EventArgs) Handles CreateProfileButton.Click 

    profileCommand.Connection = profileConnection 
    profileCommand.CommandText = "select Email from Players where Email = '" & EmailTextBox.Text & "'" 
    Dim profileDataReader As OleDbDataReader = profileCommand.ExecuteReader() 'getting error on this line 

    If profileDataReader.Read() Then 
     MsgBox("This email already exits.") 
     profileDataReader.Close() 
     Exit Sub 
    End If 
+1

你在哪裏打電話profileConnection.Open? – Steve

+0

我不認爲我叫 – Sharukh

+1

這段代碼很瘋狂 - 容易受到SQL注入攻擊。它實際上是乞求被黑客攻擊。 –

回答

1

錯誤是相當清楚的。要執行你需要有與命令打開相關聯的連接的任何命令。這樣做是調用的打開方法在調用Open方法之前,你應該告訴你的連接在哪裏打開數據庫,通過「ConnectionString」傳遞給你的連接

添加到這個代碼有需要修正的

Private Sub CreateProfileButton_Click(sender As Object, e As EventArgs) Handles CreateProfileButton.Click 

    Using profileConnection = New OleDbConnection(... connectionstring...) 
    Using profileCommand = New OleDbCommand() 
     profileConnection.Open() 
     profileCommand.Connection = profileConnection 
     profileCommand.CommandText = "select Email from Players where Email = ?" 
     profileCommand.Parameters.Add("@p1", OleDbType.VarWChar).Value = EmailTextBox.Text 
     Using profileDataReader = profileCommand.ExecuteReader()  
     ..... 
     End Using 
    End Using 
    End Using 
End Sub 

在這段代碼中我已刪除的連接和該命令的全局變量和創建它們本地的單擊事件中的其他問題。連接,命令和閱讀器被封閉在使用塊中,以確保正確關閉和處理對象。最後,查詢文本現在被參數化以避免Sql注入和解析問題。

相關問題