There is already an open DataReader associated with this Connection which must be closed first. -------------------- 这条语句出了错: -------------------------
SqlDataReader sqldrdataReader = sqlCommArrayList.ExecuteReader();
---------------------我的代码如下: ---------------------------using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;namespace CSWEB
{
/// <summary>
/// LeaveWord 的摘要说明。
/// </summary>
public class LeaveWords
{
private SqlConnection sqlConn;
private SqlCommand sqlComm;
private SqlDataAdapter sqlDA;
private SqlCommandBuilder sqlcbCmdBuilder; public LeaveWords()
{
sqlConn = new SqlConnection("Initial Catalog=tmpGuest;Data Source=192.168.1.80;User ID=sa;Password=");
sqlConn.Open();
sqlComm = new SqlCommand();
sqlComm.Connection = sqlConn;
sqlDA = new SqlDataAdapter();
sqlcbCmdBuilder = new SqlCommandBuilder(sqlDA);
}

public bool AddWorld(string sTitle,string sContents)
{
DataSet dataSet = new DataSet();
DataRow drNewRow;
sqlComm.CommandText = "Select * from LeaveWord";
sqlDA.SelectCommand = sqlComm;
sqlDA.Fill(dataSet);
drNewRow = dataSet.Tables[0].NewRow();
drNewRow[1] = sTitle;
drNewRow[2] = sContents;
dataSet.Tables[0].Rows.Add(drNewRow);
try
{
sqlDA.Update(dataSet);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
return false;
}
return true;
} public ArrayList getAllRow()
{
ArrayList alDatas = new ArrayList();
SqlCommand sqlCommArrayList = new SqlCommand();
sqlCommArrayList.Connection = sqlConn;
sqlCommArrayList.CommandText = "Select * from LeaveWord";
SqlDataReader sqldrdataReader = sqlCommArrayList.ExecuteReader();
while(sqldrdataReader.Read())
{
LeaveWord lwLeaveWorld = new LeaveWord(sqldrdataReader.GetString(1),sqldrdataReader.GetString(2));
alDatas.Add(lwLeaveWorld);
}
return alDatas;
} ~LeaveWords()
{
if (sqlConn.State != ConnectionState.Closed)
{
sqlConn.Close();
}
}
} public class LeaveWord
{
public string sTitle;
public string sContents;
public LeaveWord(string sTitle,string sContents)
{
this.sTitle = sTitle;
this.sContents = sContents;
}
}
}
/////////////////////////////////////////////////////////
/* 
当我调用getAllRow() 后就出错了。
请问,这到底是什么问题!?
*/

解决方案 »

  1.   

    sqldrdataReader没有close在用完后要关闭
      

  2.   

    1. sqldrdataReader.Close ();2. C#里面析构函数未必执行。  sqlConn.Close();要写在getAllRow() 里面.3. SqlDataAdapter 不需要 sqlConn.Open(); 4. sqlConn.Open(); 只要在这句之前就行了.
    SqlDataReader sqldrdataReader = sqlCommArrayList.ExecuteReader();=======================================
    但愿雨水皆化酒,只恨今生已非人。
      

  3.   

    reader read 玩了都要关掉,否则占用dataconnection
      

  4.   

    c#里面最好还是不要像c++一样把垃圾收集放在析构函数中,而是尽量让CLR自己自动执行垃圾收集。因为析构函数等于实现了Finalization(),它需要被显式调用而且绕开CLR的垃圾收集,这中方法会损伤性能。所以在你的GetAllRows中while执行完后,就关闭DataReader。再另写一个方法,关闭连接。删掉~LeaveWords()