public class db
{
    SqlConnection conn = new SqlConnection();    public int a = 100; public db()
{
      
        
        
}
    public void aa() { a=1000;}
    public int bb(){return a;}
    public SqlConnection getcon()
    {
        SqlConnection sqlcon = new SqlConnection();        sqlcon.ConnectionString = "server=.\\sqlexpress;database=oushang;uid=sa;pwd=123";
        sqlcon.Open();
        return sqlcon;
    }
    public  SqlDataReader show(string str)
    {
       SqlCommand  sqlcom = new SqlCommand();        sqlcom.CommandText = str;      conn = getcon();
        sqlcom.Connection = conn ;        return sqlcom.ExecuteReader();    }
    public int num(string str)
    {
      conn  = getcon();
      SqlCommand  sqlcom1=new SqlCommand (str,conn );        return  Convert.ToInt32 (sqlcom1.ExecuteScalar()) ;
    }
   
}
假设我先调用show()方法。这时代码执行到     conn = getcon();这时调用getcon()方法,让一个SqlConnection对象有赋值给conn然后调 用nun()方法,代码执行到conn=getcon()时,这时赋值的连接对象应该和show的连接对象不是同一个吧?这就是为什么不会引起独占连接的原因?

解决方案 »

  1.   

    当然不会SqlConnection conn = new SqlConnection();
      

  2.   

    不同连接
    SqlDataReader是独占连接的 
      

  3.   

    你的代码有 sqlcon.Open(),其实令人担心的是,什么时候执行 sqlcon.Close() 呢?如果不能尽可能及时关闭逻辑连接,怎么能把连接池中的物理连接共享给别的请求使用呢?
      

  4.   

    2个不同连接。 它们都是独占的。
    SqlDataReader是独占连接的