String sql = "SELECT * from mybrknElements; ";
String sql2 = "";
String sWord = "" ;
String sNum = "" ;
int nWords = 0;
cnn.Close();
cnn.Open();
SqlCommand command = new SqlCommand(sql, cnn);
cnn2.Close();
cnn2.Open();
SqlDataReader drb;
drb = command.ExecuteReader();
while (drb.Read())
{
sNum = drb["ID"].ToString();
sWord = drb["Element"].ToString();
MessageBox.Show("OUTER loooop sNum = " + sNum + " sWord = " + sWord);
sql2 = "SELECT * from mybrknElements2; ";
String sWord2 = "" ;
String sNum2 = "";
SqlCommand command22 = new SqlCommand(sql2, cnn2);
SqlDataReader drcc;
drcc = command22.ExecuteReader(); //ERROR comes up after this line
while (drcc.Read())
{
sNum2 = drcc["ID"].ToString();
sWord2 = drcc["Element"].ToString();
if (Equals(sWord2,sWord2))
{
nWords = nWords + 1;
MessageBox.Show("sNum2 = " + sNum2 + " sWord2 = " + sWord2);
}
}
//---check occurances--------------
}
上面是我的代码:我使用了2个SqlDataReaders,其中一个在其他内部 我在while循环结束时收到错误 :已经有一个与此命令关联的打开DataReader,必须先关闭
有人可以帮忙吗? 谢谢。
答案 0 :(得分:0)
试试这段代码,
SqlDataReader drb;
drb = command.ExecuteReader();
while (drb.Read())
{
sNum = drb["ID"].ToString();
sWord = drb["Element"].ToString();
MessageBox.Show("OUTER loooop sNum = " + sNum + " sWord = " + sWord);
sql2 = "SELECT * from mybrknElements2; ";
String sWord2 = "" ;
String sNum2 = "";
SqlCommand command22 = new SqlCommand(sql2, cnn2);
SqlDataReader drcc;
drcc = command22.ExecuteReader(); //ERROR comes up after this line
drb.Close();
while (drcc.Read())
{
sNum2 = drcc["ID"].ToString();
sWord2 = drcc["Element"].ToString();
if (Equals(sWord2,sWord2))
{
nWords = nWords + 1;
MessageBox.Show("sNum2 = " + sNum2 + " sWord2 = " + sWord2);
}
}
drcc.Close();
}
答案 1 :(得分:0)
您应该停止重复使用命令和连接对象,并在使用它们后正确处理它们。重用对象没有任何好处(.NET无论如何都会通过连接池重用开放套接字到数据库,即使是差异连接对象),也只会导致这样的问题。
因此,如果不重复使用对象,并正确处理对象,您的代码可能最终会像:
string sql = "SELECT ID, Element FROM mybrknElements; ";
string sql2 = "SELECT ID, Element FROM mybrknElements2;";
int nWords = 0;
string connectionString = "Your Connection String";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql1, connection))
{
connection.Open();
using (var reader = command.ExecuteReader())
{
string sWord = reader.GetString(0);
string sNum = reader.GetString(1);
using (var connection2 = new SqlConnection(connectionString))
using (var command2 = new SqlCommand(sql2, connection2))
{
connection2.Open();
using (var reader2 = command2.ExecuteReader())
{
string sWord2 = reader2.GetString(0);
string sNum2 = reader2.GetString(1);
if (Equals(sWord1,sWord2))
{
nWords++;
}
}
}
}
}
N.B。在每个数据读取器中,您只使用两列,因此我已将这些列添加到每个SQL语句的选择列表中,这样您就不会不必要地检索永远不会使用的数据。
整个循环让我感到毫无意义和低效,但假设整个目的是让nWords
得到正确的数字,你可以在SQL中完成所有这些:
SELECT nWords = COUNT(*)
FROM mybrknElements AS e
INNER JOIN mybrknElements AS e2
ON e2.ID = e.ID;