【发布时间】:2017-09-05 09:04:21
【问题描述】:
这让我很头疼。我知道这个问题(或至少它的变体)已被问过很多次,但在将其标记为重复之前,请考虑以下代码:
string myConnectionString = myConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ToString();
SqlConnection mySQLConnection;
SqlCommand mySQLCommand;
SqlDataReader mySQLDataReader;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
mySQLCommand = new SqlCommand("SELECT TOP 1 * FROM Table ORDER BY Id DESC", mySQLConnection);
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
using(mySQLDataReader = mySQLCommand.ExecuteReader())
{
if (mySQLDataReader.HasRows)
{
if (mySQLConnection.State == ConnectionState.Open)
{
while (mySQLDataReader.Read())
{
//Perform Logic : If the last record being returned meets some condition then call the below method
MethodCalled();
}
}
}
}
MessageBox.Show("Connection state: " + mySQLConnection.State);
}
我想找到一种方法:
- 读完后关闭读卡器
- 当
while-loop读完并且没有剩余行时,退出它
但我只是不断收到SqlException 说明以下内容:
阅读器关闭时调用 read 的尝试无效
仅从广泛的观察来看,我可以追踪到该错误是由于我返回的数据仅包含一行。问题在于,在读取该行之后,编译器会返回到While(mySQLDataReader.Read()){} 并尝试读取一个不包含任何行的表。
我尝试了以下方法:
-
将命令对象中的
ExecuteReader()包装在using块中,以便在完成读取后分别自动关闭读取器和连接:using(mySQLDataReader = mySQLCommand.ExecuteReader()) { //Logic performed } -
就在
while-loop的右大括号之前,我尝试检查是否有更多行从 sql 命令留下/返回,并在满足该条件后中断循环:if(mySQLDataReader.HasRows == false) //No more rows left to read { break; //break out of loop }
两次尝试均未成功。我该如何解决这个问题?
【问题讨论】:
-
这很奇怪。我已经使用过无数次了。
Read()函数在数据末尾返回false并且不抛出异常。你能发布更多代码让我们看看你在做什么吗? -
您能否发布一个突出您的问题的最小示例?
-
能否提供更多代码?看来您正在尝试将
Read超出using(...) {}范围:using(mySQLDataReader = mySQLCommand.ExecuteReader()) {...} ... mySQLDataReader.Read(); -
您能否发布您正在使用的复制此错误的整个代码块?
-
你用
//Logic performed替换的代码是什么?它应该类似于while(mySQLDataReader.Read()) { /* do stuff with rows */ }。Read()方法在还有要读取的行时返回 true,在读取最后一行时返回 false。