【问题标题】:SqlDataReader is not returning any data but query worksSqlDataReader 不返回任何数据,但查询有效
【发布时间】:2018-07-27 06:39:46
【问题描述】:

我在从 MSSQL 数据库中提取数据时遇到问题。当我使用 SQL Studio 编写语句时,它工作正常并返回超过 500 条记录,但读取结果始终为空。

这是我的自动取款机。

internal static void GetEntities(EntityRequest request, ref EntityResponse response)
    {
        string connString = @"server=DESKTOP-MCPU420\SQLEXPRESS;Initial Catalog=Skyline;Integrated Security=True";
        try
        {
            using (SqlConnection sqlConn = new SqlConnection(connString))
            {

                string query = null;
                if (request.Expression.OrderBy == null)
                    query = string.Format("SELECT {0} FROM {1} WHERE {2};",
                        request.Expression.Columns, request.Expression.TableName, request.Expression.Where);
                else
                    query = string.Format("SELECT {0} FROM {1} WHERE {2} ORDER BY {3};",
                        request.Expression.Columns, request.Expression.TableName, request.Expression.Where, request.Expression.OrderBy);

                using (SqlCommand command = new SqlCommand(query, sqlConn))
                {
                    sqlConn.Open();

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                            response.Content.Add((IDataRecord)reader);
                    }
                }
            }

        }
        catch (Exception e)
        {
            ErrorMessageProvider.SetResponseMessage(ref response, ErrorList.PROGRAM_FAILED, request.Language);
            response.ErrorMessage = e.ToString();
        }
    }

这个查询进入:

SELECT Id
    ,IATACode
    ,AgentName
    ,CASSCode
    ,HomeAirport_Id
FROM dbo.CLI_Agent
WHERE IATACode LIKE '%'
    AND AgentName LIKE '%'
    AND CASSCode LIKE '%';

来自 SQL 工作室的结果 Link to image

任何帮助将不胜感激。

【问题讨论】:

  • 你确定(你能调试这个吗?)这条线工作:response.Content.Add((IDataRecord)reader);应该更像stackoverflow.com/questions/13860490/…
  • 你能告诉我们你传递的参数吗?
  • Response.Content.Add 是做什么的?如果它存储传入的对象,而不是读取所有列,那将不起作用,因为DataReaderIDataRecord 接口只是为您提供了当前记录的视图。当阅读器离开时,这个“数据记录”将不再有任何内容。
  • 您的 SQL 看起来正确,但您还有其他问题,您没有关闭连接。
  • @WynDiesel 参数此时实际上是空的,正如您在我发布的那个 SQL 查询中看到的那样,这就是在数据库上执行的内容。

标签: c# sql sql-server sqldatareader


【解决方案1】:

连接字符串有一点问题。我修复了它,现在它可以工作了。它总是归结为错误的种类:-)

新连接。字符串:

string connString = @"Data Source=DESKTOP-MCPU420\SQLEXPRESS;Initial Catalog=Skyline;Integrated Security=True;";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多