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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…