gpt4 book ai didi

c# - 返回 SqlDataReader

转载 作者:行者123 更新时间:2023-11-30 18:58:58 25 4
gpt4 key购买 nike

我正在尝试通过引用传递给读者或让读者返回。我在返回时遇到了问题。

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());
}

但是我得到以下错误

Invalid attempt to call HasRows when reader is closed.

有什么想法吗?

最佳答案

问题是:

finally
{
conn.Close();
}

您将在方法返回之前关闭连接。如果没有打开的连接,读取器将无法运行。

(鉴于您只在返回时使用它,所以根本不清楚为什么您有 reader 变量。)

在本身打开连接的方法中返回 SqlDataReader 通常很棘手 - 因为这意味着您没有关闭连接的好方法。更好的方法是让调用者传递连接,此时您可以:

using (var connection = new SqlConnection(...))
{
using (var reader = QaqcsqlLib.GetSql(connection, "job", "Task1"))
{
// Use the reader here
}
}

编辑:正如 Scott 所指出的,您对 CommandBehavior.CloseConnection 的使用允许关闭阅读器以关闭连接。但是,它使其他事情变得更加棘手。例如,如果发生异常,您必须处理连接(因为那样调用者将没有机会),但不会否则 - 我仍然更喜欢我的方法。

关于c# - 返回 SqlDataReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16468379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com