我试图通过引用传递读者或返回一个.我在回归时遇到了问题.
public static SqlDataReader GetSql(string businessUnit, string taskId)
{
const string connstring = "Connection string";
SqlConnection conn = new SqlConnection(connstring);
SqlCommand command = new SqlCommand();
SqlDataReader reader;
try
{
conn.Open();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText =
"SELECT * FROM Audits WHERE BusinessUnit = @BU AND TaskID = @TID";
command.Parameters.AddWithValue("@BU", businessUnit);
command.Parameters.AddWithValue("@TID", taskId);
return reader = command.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
SqlDataReader reader = QaqcsqlLib.GetSql("job", "Task1");
if (reader.HasRows)
{
while (reader.Read())
MessageBox.Show(reader[0].ToString());
}
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误
读取器关闭时无效尝试调用HasRows.
有任何想法吗?
Jon*_*eet 11
这就是问题:
finally
{
conn.Close();
}
Run Code Online (Sandbox Code Playgroud)
您在方法返回之前关闭连接.没有开放连接,读者将无法运行.
(目前尚不清楚为什么你有reader变量,因为你只在返回时使用它.)
返回一个SqlDataReader本身打开连接的方法通常很棘手 - 因为这意味着你没有一个很好的方法来关闭连接.更好的方法是让调用者通过连接,此时你可以:
using (var connection = new SqlConnection(...))
{
using (var reader = QaqcsqlLib.GetSql(connection, "job", "Task1"))
{
// Use the reader here
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:正如斯科特所说,你的使用CommandBehavior.CloseConnection 将允许关闭阅读器以关闭连接.然而,它使其他事情更棘手.例如,如果发生异常,你必须处理连接(因为那时调用者没有机会),但不是这样 - 我仍然更喜欢我的方法.