There is one paradigm for resource usages optimization:- Acquire late and release early. considering this paradigm. I always see the following sequence to db call :
- open conneciton
- create command
- do validation
- set parameter
- finally execute command
Is anythng wrong if I do?
- create command
- do validation
- set parameter
- open conneciton
- finally execute command
e.g
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "cus";
cmd.CommandType = CommandType.StoredProcedure;
//Configure input parameters
SqlParameter param = new SqlParameter();
param = cmd.Parameters.Add(new SqlParameter("@id", 2));
param.Direction = ParameterDirection.Input;
SqlConnection conn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI; Initial Catalog=SpringApp;");
conn.Open();
cmd.Connection = conn;
cmd.Prepare();
SqlDataReader reader = cmd.ExecuteReader();
Yes, the second sequence is better. How much depends on how much work goes into 1,2,3. I usually would not consider CreateCommand and SetParameter as big issues but Validation might require some time and it might even lead to canceling the whole thing. A pity if you have already opened the Connection and then find out the data is invalid.