日期:2014-05-17  浏览次数:20393 次

关闭没有的DataReader
这是出错代码的类
C# code

 public  static class DBHelper
    {
        private static SqlConnection connection;
   //private static SqlDataAdapter da;
        public static SqlConnection Connection
        {
            get
            {
                string connectionString = ConfigurationManager.ConnectionStrings["XCgo"].ConnectionString;
                if (connection == null)
                {
                    connection = new SqlConnection(connectionString);
                    connection.Open();
                }
                else if (connection.State == System.Data.ConnectionState.Closed)
                {
                    connection.Open();
                }
                else if (connection.State == System.Data.ConnectionState.Broken)
                {
                    connection.Close();
                    connection.Open();
                }
                return connection;
            }
        }
      public static DataTable GetDataTable(string safeSql)
        {
            DataSet ds = new DataSet();
            SqlCommand cmd = new SqlCommand(safeSql, Connection);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            cmd.Dispose();

                da.Fill(ds);//异常出在这里,提示There is already an open DataReader associated with this Command which must be closed first. 


      
            da.Dispose();
          
            connection.Close();
            return ds.Tables[0];
        }
}



我在前台频繁点一个连接调用这个GetDataTable方法就会报一个datareader未关闭的错误,但是这个方法里没用到datareader

------解决方案--------------------
获取datatable的底层还是使用datareader来读取的,所以会报那个错
那个错的来源是因为你把SqlConnection 定义为了static,数据层连接绝对不能这样做的
这样做意味着你的数据库一直处于一个单连接,并发的时候报错无疑