I don't know whether this function should (or could) be described as an 'optimized method'
Anyhow, need some advices regarding on how to close an SqlConnection without wasting too much resources
public object MethodName(){
object retVal=new object();
string sql="";
SqlConnection sConn=new SqlConnection();
SqlCommand sCmd=new SqlCommand();
try{
using (sConn=new SqlConnection(CONNECTION_STRING)){
sql="SELECT * FROM [TABLE_NAME]";
sCmd=new SqlCommand(sql, sConn);
sConn.Open();
try{
retVal=sCmd.ExecuteScalar();
}
catch{
}
}
return retVal;
}
catch{
throw;
}
finally{
if (sConn!=null)
sConn.Close();
}
}
Do I really have to put the code within the 'finally' scope?
My intention was to close the connection if there's any exception been thrown
Any advices/comments would be highly regarded
Loading
Dy OswaldPosted Mar 23, 2008, 10:32 PM
Thanks for your advices/comments
Anyway, I found a nice article about this topic, Badillos' blog about connection pool
http://blogs.msdn.com/angelsb/archive/2004/08/25/220333.aspx
In case you're interested
Josip MajicPosted Mar 19, 2008, 8:44 AM
You can wrap up the SQLCommand object in a using statement too so no cleanup is needed. Also, put the try around everything so you catch any potential connectivity errors:
try{
using (SqlConnection conn = new SqlConnection(Connections.SQLDataConnection)){
// Open connectionconn.Open();
// New command using (SqlCommand cmd = conn.CreateCommand()){
CommandType.Text;cmd.CommandText =
"SELECT * FROM [TABLE_NAME]"; // Execute return cmd.ExecuteScalar();}
}
}
catch (Exception ex){
// Rethrow throw new Exception("Unhandled error.", ex);}
Scott LyslePosted Mar 15, 2008, 4:58 AM