首页 > 解决方案 > SSMS 中的 SQL 查询有效,但在 C# 中无效

问题描述

我有这个查询,它返回存储在 MS SQL 数据库中的图像。如果我在 SSMS (SQL Management Studio) 中运行它,它会完美运行并立即返回。

select image from extra where product_id = 184

但是在 .NET Core MVC 中它不会返回,并且 SQL 命令只是超时,并且会出现错误 500,说明 SQL 命令超时。我什至给了它整整 10 分钟的时间来“返回” SQL 命令,但它仍然没有。

[HttpGet("{id}/image")]
public object Get(int id)
{
    using (SqlConnection connection = new SqlConnection(connectionstring)) {
        using (SqlCommand sqlCommand = new SqlCommand("select top 1 image from extra where product_id = @product_id", connection))
        {
            sqlCommand.Parameters.AddWithValue("@product_id", id);
            sqlCommand.Connection.Open();
            using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
            {
                object img = null;

                if (sqlDataReader.HasRows)
                {
                    sqlDataReader.Read();
                    img = new
                    {
                        image = sqlDataReader["image"] == DBNull.Value ? null : "data:image/png;base64," + Convert.ToBase64String((byte[])sqlDataReader["image"])
                    };

                    return img;
                }
            }
        }
    }

    return new { error = true, message = "Unknown error in image getting" };
}

在调试模式下单步执行代码。它没有超过这条线:

SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

如果我在 SSMS 中运行它,这个pastebin就是 SQL 查询返回的内容。

编辑:SQL版本是Microsoft SQL Server 2017 (RTM-CU15-GDR) (KB4505225) - 14.0.3192.2 (X64) Jun 15 2019 00:45:05 Copyright (C) 2017 Microsoft Corporation Standard Edition (64-bit) on Windows Server 2012 R2 Standard 6.3 <X64> (Build 9600: ) (Hypervisor)

标签: c#sql-server.net-core

解决方案


请在下面尝试。

还要在 Catch 上放一个断点,看看是ex.Message什么

try
            {
                SqlCommand sqlCommand = new SqlCommand("select top 1 image from extra where product_id = @product_id", connection);
                sqlCommand.Parameters.Add(new SqlParameter("@product_id", id));
                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        img = new
                        {
                            image = sqlDataReader["image"] == DBNull.Value ? null : "data:image/png;base64," + Convert.ToBase64String((byte[])sqlDataReader["image"])
                        };
                        connection.Close();
                        return img;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return new { error = true, message = "Unknown error in image getting" };

推荐阅读