【问题标题】:Invalid attempt to call Read when reader is closed. vb.net阅读器关闭时调用 Read 的尝试无效。 VB.net
【发布时间】:2014-08-14 07:33:44
【问题描述】:

我的 WinForm 中有这个子:

Public Function CheckSentToday(ByVal date1 As DateTime) As Boolean
    Dim cmSql As New SqlCommand("Check_Today", cnSql)
    Try
        cmSql.CommandType = CommandType.StoredProcedure
        cmSql.Parameters.AddWithValue("@date1", String.Format("{0:yyyy-MM-dd}", date1))
        If Not cnSql Is Nothing AndAlso cnSql.State = ConnectionState.Closed Then cnSql.Open()
        If cmSql.ExecuteScalar IsNot Nothing Then
            Return True
        Else
            Return False
        End If
    Catch ex As Exception
        WriteToText("CheckSentToday", ex.ToString)
        CheckSentToday = False
    Finally
        If Not cnSql Is Nothing AndAlso cnSql.State = ConnectionState.Open Then cnSql.Close()
    End Try

End Function

我在执行SqlCommand之前打开连接,

并在finally 子句中关闭连接

不过,每次调用这个 sub 时它都会返回以下错误:

Description:System.InvalidOperationException: Invalid attempt to call Read when reader is closed.
   at System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout)
   at System.Data.SqlClient.SqlDataReader.Read()
   at System.Data.SqlClient.SqlCommand.CompleteExecuteScalar(SqlDataReader ds, Boolean returnSqlValue)
   at System.Data.SqlClient.SqlCommand.ExecuteScalar()

谁能帮我找出原因?

任何帮助将不胜感激

【问题讨论】:

    标签: vb.net ado.net sqlconnection sqlcommand


    【解决方案1】:

    改用Using-statement,不要重复使用SqlConnection

    Public Function CheckSentToday(ByVal date1 As DateTime) As Boolean
        Using cnSql = New SqlConnection("connection-string")
            Using cmSql As New SqlCommand("Check_Today", cnSql)
                cmSql.CommandType = CommandType.StoredProcedure
                cmSql.Parameters.AddWithValue("@date1", String.Format("{0:yyyy-MM-dd}", date1))
                Try
                    cnSql.Open()
                    If cmSql.ExecuteScalar IsNot Nothing Then
                        Return True
                    Else
                        Return False
                    End If
                Catch ex As Exception
                    WriteToText("CheckSentToday: ", ex.ToString)
                    CheckSentToday = False
                End Try
            End Using
        End Using
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      相关资源
      最近更新 更多