ExecuteReader需要一个开放且可用的连接VB.NET

时间:2015-11-22 21:18:50

标签: .net vb.net visual-studio

我正在尝试在我的数据库中创建和保存配置文件详细信息,但是我收到一条错误消息,“ExecuteReader需要一个开放且可用的连接。连接的当前状态已关闭。任何帮助将不胜感激。这里是我的代码。

 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 个答案:

答案 0 :(得分:1)

错误很清楚。要执行任何命令,您需要将连接与命令Open相关联。这是在执行命令之前调用连接的Open方法完成的。但在调用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

在这段代码中,我删除了连接和命令的全局变量,并在click事件中本地创建了它们。连接,命令和阅读器都包含在使用块中,以确保正确关闭和处理对象。最后,查询文本现在被参数化,以避免Sql注入和解析问题。

相关问题