c# - 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)
解决方案
请在下面尝试。
还要在 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# - Unity-将图像上传到 Firebase 存储后如何获取下载 URL?
- postgresql - 如何修复“缺少表的 FROM 子句条目”错误
- sql-server - 无法从 base64 转换为任何有意义的东西
- java - 即使标签具有不同的值,如何确定两个 XML 文件是否具有相同的结构?
- java - 如何修复 Spring Boot 中的“postgresql 配置”null 错误
- java - 如何将多个列表中的值写入新的 csv 文件?
- javascript - SVG 变形不平滑变形 - 动漫 js
- python - 如何从 python 中的 xml 文件中获取文本?
- python - Sqlalchemy 与动态条件的关系
- dart - Dart http:无法解析标头值(www-authenticate)