我有这个查询,它返回存储在 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" };
}
在 Debug模式下单步执行代码。它不会超过这一行:
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
这pastebin是在 SSMS 中运行时 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)
最佳答案
请尝试以下。
同样在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" };
关于c# - SSMS 中的 SQL 查询有效但在 C# 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58029271/