Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

.net - SQL Server not opening table within using - ExecuteScalar

Public Function ExecuteScalar_Sql(ByVal ConnectionString As String, ByVal QueryString As String, Optional ByRef Parameters As List(Of Object) = Nothing) As (Result As String, Success As Boolean, Message As String)
    Dim Success As Boolean = False
    Dim Message As String = Nothing
    Dim Result As String = Nothing
    Try
        Using cn As New System.Data.SqlClient.SqlConnection(ConnectionString)
            Using cmd As New System.Data.SqlClient.SqlCommand(QueryString, cn)
                If Parameters IsNot Nothing Then Parameters.ForEach(Sub(param As Object)
                                                                        cmd.Parameters.Add(param.Name, param.Value)
                                                                    End Sub)
                Result = cmd.ExecuteScalar().ToString
                Success = True
            End Using
        End Using
    Catch ex As Exception
        Message = ex.Message
    Finally

    End Try
    Return (Result, Success, Message)
End Function

I get this error:

'ExecuteScalar requires an open and available Connection. The connection's current state is closed

However I can use similar code for ExecuteNonQuery and it works.

If remove from within the Using I can get to work, just curious why it doesn't work within Using.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...