SqlConnection MyConnection1;
public SqlConnection MyConnection
{
get
{
 MyConnection1 =new SqlConnection(ConfigurationSettings.AppSettings["cnFriends.ConnectionString"]);
MyConnection1.Open();
return MyConnection1;
}
}
public  SqlConnection DbCloseed()
{
MyConnection1.Close();
return MyConnection1;
}
使用时
public j forma= new j();
SqlCommand myCommand= new SqlCommand("proc_per_login",forma.MyConnection);
forma.DbCloseed();可以的话 我就大量使用了!!!

解决方案 »

  1.   

    SqlConnection MyConnection1;
    public SqlConnection MyConnection
    {
    get
    {
    if (MyConnection1  == null)
    {
     MyConnection1 =new SqlConnection(ConfigurationSettings.AppSettings["cnFriends.ConnectionString"]);
    MyConnection1.Open();
    }
    return MyConnection1;
    }
    }
      

  2.   

    楼上为什么要if (MyConnection1  == null)?我考虑如果文件中大量使用

    SqlCommand myCommand3 = new SqlCommand("select count(id) from company" ,forma.MyConnection); 
    int totel_com=(int)myCommand3.ExecuteScalar();
    Label1.Text=totel_com.ToString();
    SqlCommand myCommand4 = new SqlCommand("select count(id) from zp" ,forma.MyConnection); 
    int totel_zp=(int)myCommand4.ExecuteScalar();
    Label2.Text=totel_zp.ToString();
    SqlCommand myCommand5 = new SqlCommand("select count(id) from person" ,forma.MyConnection); 
    int totel_per=(int)myCommand5.ExecuteScalar();
    Label3.Text=totel_per.ToString();
    SqlCommand myCommand6 = new SqlCommand("select count(id) from person where iname<>'null'" ,forma.MyConnection); 会不会打开多个 SqlConnection 造成资源浪费而崩溃?
      

  3.   

    数据库打开一次即可对数据库各种对象操作,当不需要的时候再将其释放,何况同一连接对象在已经打开的情况下再次调用Open也会出错
      

  4.   

    那我那么写不就会出错了吗??
    每用一次forma.MyConnection
    使用2次forma.MyConnection
    都有一个OPEN
    一个对象不是有2个OPEN了?
    可是实际我测试到没有问题啊???
      

  5.   

    你写的,不会出错。
    但都不会这样写,不要一直开着这个连接用它。在用的地方打开,用完马上关。ado.net使用的是连接池,初次建立连接后,只要连接串不变,在连接池里就有了这个东东。你用的时候只是去连接池里取,
    最后只是把数据库连接释放回了连接池在后来的事,就是GC的事了。你就不用管了
      

  6.   

    我的可能不太合乎规范
    应该在写个OPEN方法
    但这个也不会错 也不会影响效率
    对吧
      

  7.   

    SqlConnection MyConnection1;
    public SqlConnection MyConnection
    {
    get
    {
     MyConnection1 =new SqlConnection(ConfigurationSettings.AppSettings["cnFriends.ConnectionString"]);
    return MyConnection1;
    }
    }
    public  SqlConnection Dbclose()
    {
    MyConnection1.Close();
    return MyConnection1;
    }
    public  SqlConnection DBopen()
    {
    MyConnection1.Open();
    return MyConnection1;
    }
    结果却
    ----------------
    未将对象引用设置到对象的实例。 
    说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。源错误: 
    行 268: {
    行 269:
    行 270: MyConnection1.Open();
    行 271: return MyConnection1;