错误帮助:已经有一个与此命令关联的打开DataReader,必须先关闭它。

时间:2014-06-26 07:38:03

标签: .net sql-server vb.net ado.net database-connection

我在这部分代码中遇到此错误,而我仍然无法找到解决方案

错误统计信息:

  

ExecuteReader需要一个开放且可用的连接。该   连接的当前状态是开放的。

源代码在:

  

第144行:.CommandType = CommandType.Text

     

第145行:.Connection = cn

     

第146行:dr = .ExecuteReader

     

第147行:以

结束      

第148行:

代码是:

 Public Function GetDBField(ByVal Query As String, ByVal Field As String) As String

    'abriendo la conexion a la base de datos

    SqlConnect()

    Dim cmd As New SqlCommand
    Dim result As String = ""

    Dim dr As SqlDataReader
    dr = Nothing

    'ejecutando el lector de DO
    Try

        With cmd
            .CommandText = Query
            .CommandType = CommandType.Text
            .Connection = cn
            dr = .ExecuteReader
        End With



    Catch ex As SqlException
        ShowAlertMessage(ex.Message)
        GetDBField = Nothing
        Exit Function
    End Try

    'Escribiendo en una Variable de texto
    Try
        If dr.HasRows Then

        End If
        While dr.Read
            If IsDBNull(dr(Field).ToString) = True Then
                result = Nothing
            Else
                result = dr(Field).ToString
            End If
        End While
    Catch ex As SqlException
        ShowAlertMessage(ex.Message)
        GetDBField = Nothing
        Exit Function

    End Try

    'Cerrando la conexion de BD
    SqlDisconnect()

    GetDBField = result
End Function

真的需要任何帮助

在重播上一个问题时,所有这些代码都在App_Code的vb页面中

#Region "   Variables Globales"
    Public db As String = "repuestosdr"

    'Public CnStr As String = "Driver={SQL Server Native Client 10.0};Server=localhost;Database=" & db & ";Uid=crivera;Pwd=crivera;"
    Public CnStr As String = ConfigurationManager.ConnectionStrings("SuoodConnection").ConnectionString    '"Driver={SQL Server};Server=repuestosdr.db.10580944.hostedresource.com;Database=" & db & ";Uid=" & db & ";Pwd=r34llyH4rd!;Port=1433;"

    Public Logged As Boolean = False

    Public Qry As String
    Public msg As New MsgBoxResult


    Public ds As New DataSet
    Public dt As New DataTable
    Public dr As SqlDataReader
    Public cn As New SqlConnection()
    Public da As New SqlDataAdapter
    Public cmd As SqlCommand


#End Region

用于连接:

#Region "   Connection"
    Public Function SqlConnect(Optional ByVal MyPage As Page = Nothing) As Boolean
        Try
            If cn.State = ConnectionState.Closed Then
                With cn
                    .ConnectionString = CnStr
                    .Open()
                End With
            End If

        Catch myerror As Exception
            ShowAlertMessage("Error Connecting to the Database" & Chr(13) & myerror.Message)
            SqlConnect = False
        End Try
        SqlConnect = True
    End Function

0 个答案:

没有答案