gpt4 book ai didi

c# - 从方法返回数据读取器

转载 作者:太空狗 更新时间:2023-10-29 19:49:07 26 4
gpt4 key购买 nike

我有以下方法

    public static SqlDataReader MenuDataReader(string url)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("spR_GetChildMenus", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@PageUrl", url);
cmd.Parameters.AddWithValue("@MenuId", ParameterDirection.Output);
cmd.Parameters.AddWithValue("@ParentId", ParameterDirection.Output);
cmd.Parameters.AddWithValue("@TitleText", ParameterDirection.Output);
cmd.Parameters.AddWithValue("@ExternalUrl", ParameterDirection.Output);
cmd.Parameters.AddWithValue("@FullUrl", ParameterDirection.Output);
cmd.Parameters.AddWithValue("@ChildCount", ParameterDirection.Output);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
//return reader;

while (reader.Read())
{
return reader;
}

}
}
}
return null;
}

我是这样调用的

        SqlDataReader reader = MenuDataReader(url);
if (reader.HasRows)
{
while (reader.Read())
{ }}

但是我收到了错误信息

Invalid attempt to call HasRows when reader is closed.

谁能帮帮我

谢谢

最佳答案

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx 所示:

  public static SqlDataReader ExecuteReader(String connectionString, String commandText,
CommandType commandType, params SqlParameter[] parameters) {
SqlConnection conn = new SqlConnection(connectionString);

using (SqlCommand cmd = new SqlCommand(commandText, conn)) {
cmd.CommandType = commandType;
cmd.Parameters.AddRange(parameters);

conn.Open();
// When using CommandBehavior.CloseConnection, the connection will be closed when the
// IDataReader is closed.
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

return reader;
}
}

关于c# - 从方法返回数据读取器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20147045/

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