已经有一个与此命令关联的开放DataReader 必须先关闭。
好。所以。我们在这里做了很多数据库读取,足以证明通用函数可以简化它。我刚刚更改了它,所以当用一个活动的函数调用时,函数不再关闭连接,因为它是一条线路。这样做,我发现了这个bug。在while
循环的第二次迭代中,DBRead函数在尝试实际执行时会出错,并按照上述错误进行抱怨。
然而。在每次迭代结束时,都有一个没有条件的reader.Close()调用。
现在......我已经做了一些环顾四周的事情,并发现了一些关于使用using
这些的事情...说实话,我不确定我会怎么做(我可以很快就弄清楚,我猜,但是,我不知道它是否能解决这个问题。
我读到的其他问题实际上并没有结束。在这种情况下,我认为我在每次打开时,在读者上调用一个关闭,然后在之后重新使用连接。我有多难?
// Find all the unprocessed gifts in the inhouse table.
SQL = "SELECT * FROM ToREgift WHERE processed = 0";
ReadCommand.Connection = ReadConnect;
ReadCommand.CommandText = SQL;
dbRERead = ReadCommand.ExecuteReader();
while (dbRERead.Read()) // Loop through them.
{
RowId = Convert.ToInt32(dbRERead["id"].ToString());
// Lookup the RE ConstituentId from the ToREConstituent table.
string ToREConstituent_Id = dbRERead["ToREConstituent_id"].ToString();
Reader = FunctionsClass.DBRead(vars.Catalog, "SELECT Constituent_Id FROM ToREConstituent WHERE ID = " + ToREConstituent_Id.ToString(), ref Connection);
Reader.Read();
string ConstituentId = Reader["Constituent_Id"].ToString();
bool UseRG = false;
try
{
UseRG = Convert.ToBoolean(dbRERead["Use_RG"]);
}
catch (Exception ex) { }
;
if (!UseRG)
{
if (dbRERead["TypeOfGift"].ToString() == "RecGiftPC")
{
UseRG = true;
}
}
AddSingleGift(ConstituentId, UseRG, RowId);
SQL = "SELECT Constituent_Id FROM ToREConstituent WHERE Id = " + ToREConstituent_Id;
dbRECommand.CommandText = SQL;
Reader = dbRECommand.ExecuteReader();
while (Reader.Read())
{
ConstituentId = Reader["Constituent_Id"].ToString();
}
Reader.Close();
}
dbRERead.Close();
--
public static SqlDataReader DBRead(string DB, string SQL, ref SqlConnection Connection)
{
SqlDataReader functionReturnValue = null;
// !! IMPORTANT !!
// This will initialise and open a connection as needed.
// The caller is responsible for closing the connection
if(Connection==null)
{
Connection = new SqlConnection();
}
if(Connection.ConnectionString=="")
{
Connection.ConnectionString = "Data Source = REDEV;Initial Catalog = " + DB + ";Integrated Security = True";
}
try
{
Connection.Open();
}
catch (Exception ex)
{
if(ex.Message!="The connection was not closed. The connection's current state is open.")
{
throw ex;
}
// Else continue, because if that's the error, doesn't matter, just move on.
}
SqlCommand dbCommand = new SqlCommand();
dbCommand.Connection = Connection;
dbCommand.CommandType = System.Data.CommandType.Text;
dbCommand.CommandText = SQL;
dbCommand.CommandTimeout = 0;
try {
functionReturnValue = dbCommand.ExecuteReader();
return functionReturnValue;
} catch (Exception ex) {
//frmMain.BatchError = true;
System.Windows.Forms.MessageBox.Show("Error reading Database. Can't Continue, sorry. Debug information below:" + vars.vbCrLf + vars.vbCrLf + ex.Message + vars.vbCrLf + SQL + vars.vbCrLf + vars.vbCrLf + Connection.ConnectionString);
Connection.Close();
System.Environment.Exit(0);
}
return functionReturnValue;
// Cleanup
//dbCommand = Nothing
}