【问题标题】:ExecuteReader requires an open and available connection VB.NETExecuteReader 需要一个开放且可用的连接 VB.NET
【发布时间】:2015-11-22 21:18:49
【问题描述】:

我正在尝试在我的数据库中创建和保存配置文件详细信息,但我收到一条错误消息,提示“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

【问题讨论】:

  • 你在哪里调用profileConnection.Open?
  • 我不认为我这么叫
  • 这段代码很容易受到sql注入攻击。它实际上是在乞求被黑。
  • 我知道哈哈。这只是我正在做的一个小项目。没什么特别的

标签: .net vb.net visual-studio


【解决方案1】:

错误很明显。要执行任何命令,您需要将连接与命令打开关联。这是在执行命令之前调用连接的 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 Injection 和解析问题。

【讨论】:

    猜你喜欢
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多