[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 730
  • Last Modified:

Closing SQL connection after return statement

Hi i have a following method
Public Function Bind() As DataSet
     Dim sqlConn As SqlConnection = New SqlConnection(CManager.AppSettings("ConnectionString"))
     Dim adapter As SqlDataAdapter = New SqlDataAdapter("Get", sqlConn)
     Dim ds As New DataSet("ds")

     adapter.SelectCommand.CommandType = CommandType.StoredProcedure
     adapter.Fill(ds)

     Return ds

     adapter.Dispose()
     sqlConn.Close()
End Function

i am closing the sql connection and disposing the dataadapter after teh RETURN statement,will any statement after return execute ...?can any one tell me whats the best approach to go about it.
Thanks
0
aspnetdev
Asked:
aspnetdev
  • 3
  • 3
3 Solutions
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
>will any statement after return execute
no.

0
 
sudheeshthegreatCommented:
No, once a return statement is encountered, all further statements are ignored. I am surprised you didnt find that out during compile time. One of the known methods to dispose/close such resource-intensive objects is to put such statements in the finally block. You may or may not want to use a catch block. Below is a code snippet. And, of course, the return statement needs to be the logically last statement of the method.
try
{
  // use the objects
}
finally
{
  // close ...
  // dispose ...
}
return ...

Open in new window

0
 
burakiewiczCommented:
you could use the using statement to do it for you
using (SqlConnection mycon = new SqlConnection(dbConn))
            {
                using (SqlDataAdapter myad = new SqlDataAdapter("Get",mycon)
                {
                    myad.SelectCommand.CommandType= CommandType.StoredProcedure;
                    myad.Fill(ds);
                }
            }
            return ds;

Open in new window

0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
sudheeshthegreatCommented:
burakiewiczDate: that's true for C#. But, if you notice the code snippet that aspnetdev shows is in VB.Net :-)
0
 
burakiewiczCommented:
didnt check that close, its in the C# section so i figured it was C#, but the using statement is also available in VB
0
 
sudheeshthegreatCommented:
'using' in vb.net? that's cool. wasnt there when i last checked.
0
 
burakiewiczCommented:
yeah its there in VS2005
heres a link from msdn. not a great one though
http://msdn2.microsoft.com/en-us/library/htd05whh(VS.80).aspx
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now