Is this necessary to open and close connection when i am using SqlDataAdapter and DataSet to get data from from table from databse in sql server? Which one will be better to use in the following code. Code1 or Code2. Please suggest me.
Code: 1 With open and colse connection
public DataSet GetFAcadSlidingImage()
{
SqlConnection con = GetConnection();
cmd = new SqlCommand("Pro_GetFAcadSlidingImage", con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex ;
}
finally
{
con.Close();
}
}
Code:2 Without open and colse connection
public DataSet GetFAcadSlidingImage()
{
SqlConnection con = GetConnection();
cmd = new SqlCommand("Pro_GetFAcadSlidingImage", con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
}