看下面代码,整个项目中是不是只创建了一个 SqlCommand对象和一个SqlDataReader对象呢,在调用类中使用了using,DB类中的SqlDataReader是不是不用close了,但是connection怎么关闭。我在看网站优化的时候见别人说,项目中尽量减少对象的创建,我第一次做项目不知道这样做好不好,网站运行没问题。
public class DB 
    {        //获取webconfig连接字符串
        public static readonly string connstr = WebConfigurationManager.ConnectionStrings["Sqlconn"].ToString();
        public SqlConnection conn = null;
        public  SqlCommand cmd = null;
        public SqlDataReader reader = null;

    //连接数据库返回SqlCommand 
        public SqlCommand GetCmd(string sql)
        {          
            conn = new SqlConnection(connstr);
            conn.Open();
            cmd = new SqlCommand(sql, conn);
            return cmd;
        }
       
        //连接数据库返回datareader
        public SqlDataReader GetReader(string sql)
        {
             reader = GetCmd(sql).ExecuteReader();
            {
                return reader;
            }
        }
    }
//DAL层一个类中的一个方法举例------------------------------------------------------
    public class Commentary
    {
        //调用公共类DB
        DB db = new DB();
        List<Model.Commentary> lm = null;
        Model.Commentary neirong = null;
        public List<Model.Commentary> GetCommentary(int NewsId)
        {
            lm = new List<Model.Commentary>();
            //存储过程    
            string sql = "exec GetCommentary @NewsId";
            using (db.cmd = db.GetCmd(sql))
            {
                db.cmd.Parameters.Add(new SqlParameter("@NewsId", NewsId));
                using (db.reader = db.cmd.ExecuteReader())
                {
                    while (db.reader.Read())
                    {                        neirong = new Model.Commentary();
                        neirong.CommentaryId = Convert.ToInt32(db.reader["CommentaryId"]);
                        neirong.CommentaryContent = db.reader["CommentaryContent"].ToString();
                        neirong.CommentaryDate = DateTime.Parse(db.reader["CommentaryDate"].ToString());
                        neirong.UserId = Convert.ToInt32(db.reader["UserId"]);
                        neirong.NewsId = Convert.ToInt32(db.reader["NewsId"]);
                        lm.Add(neirong);
                    }
                }
            }            return lm;
        }
    }

解决方案 »

  1.   

     using (db.cmd = db.GetCmd(sql))
       建议看看msdn。。使用using 会自动释放的。
      

  2.   

    GetCmd 方法不是对象,而是方法。每一此调用此方法,都(每一次)动态创建了 DBConnection 对象实例和 DBCommand 对象实例。
      

  3.   

    至于说声明几个变量,则是有些“扯”的事情。举个更简单的例子你就明白了。比如说有人在程序中前后共动态创建了5个TextBox控件,只不过非要莫名其妙地赋值给同一个变量,美其名曰“这就只创建一个控件了”。其实这就是自欺欺人。还不如用5个变量分别引用5个控件,更清晰。
      

  4.   

    不必纠结实例化多少个对象。变量用得少,就可能在不同情况下共用一个变量,可读性变差了,甚至又bug隐患。记得最晚声明,用后最早销毁就行了。