private void Page_Load(object sender, System.EventArgs e)
{
//Label1.Text="";
try
{
string myConnection = "server=local; uid =sa ;pwd =fjkdsla; database=TestSun";
string sql = "select * from books";
SqlConnection mycn = new SqlConnection(myConnection);
mycn.Open();
SqlCommand mysql = new SqlCommand(sql,mycn);
rep.DataSource = mysql.ExecuteReader();
rep.DataBind();/////////////绑定
//mycn.Close();
}
catch
{

Label1.Text="数据库连接出错,请检查!";
}
finally
{
mycn.Close();
}为什么mycn.Close();写在finally里面就不行,而是要写在上面(注释处,绑定之下!)
解决马上送分!!!

解决方案 »

  1.   

    因为mycn的定义:
    SqlConnection mycn = new SqlConnection(myConnection);
    是在Try中,而它的作用域仅局限于Try之中,所以,在Catch和Finally中不存在。
      

  2.   

    private void Page_Load(object sender, System.EventArgs e)
    {      
        SqlConnection mycn = null;
        
        try
        {
            string myConnection = "server=local; uid =sa ;pwd =fjkdsla; database=TestSun";
            string sql = "select * from books";
            mycn = new SqlConnection(myConnection)
            mycn.Open();
            SqlCommand mysql = new SqlCommand(sql,mycn);
            rep.DataSource = mysql.ExecuteReader();
            rep.DataBind();
        }
        catch
        {
            Label1.Text="数据库连接出错,请检查!";
        }
        finally
        {
            if (mycn != null)
            {
                mycn.Close();
            }
        }
    }