资源使用优化有一个范例:-获得延迟并提前发布。考虑到这种模式。我总是看到以下要执行db调用的序列:
parameter
execute命令G 211
如果我这么做有什么不对吗?
H 121最后执行命令H 222g 223
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();发布于 2012-02-15 17:11:20
是的,第二个序列更好。多少取决于1,2,3的工作量。我通常不会认为CreateCommand和SetParameter是一个大问题,但是验证可能需要一些时间,甚至可能导致取消整个任务。很遗憾,如果您已经打开了连接,然后发现数据是无效的。
发布于 2012-02-15 17:09:55
第二种情况是一条艰难的道路:
尽可能晚地打开connection ,并尽快关闭。
发布于 2012-02-15 17:17:28
是的,第二个序列很好,事实上,如果创建命令需要很长时间,那么创建命令实际上更可取,因为它使连接打开的时间更短(但是创建命令通常只需要很少的时间,因此这不会有明显的区别,因此实际上您不应该对此大惊小怪)。
我建议您在可能的情况下使用using statement,以便处理资源并使对象的生存期变得更清楚:
using (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;
using (SqlConnection conn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI; Initial Catalog=SpringApp;"))
{
conn.Open();
cmd.Connection = conn;
cmd.Prepare();
using (SqlDataReader reader = cmd.ExecuteReader())
{
}
}
}https://stackoverflow.com/questions/9297848
复制相似问题