gpt4 book ai didi

c# - 如何从 SQL Server 表中转换 TinyInt 值?

转载 作者:行者123 更新时间:2023-12-03 08:35:12 26 4
gpt4 key购买 nike

我有这个 SQL Server (Express) 表:

enter image description here

...流派 ID 为 TinyInt(最多只有几十个不同的流派)。

此 C# 代码失败,并显示“指定的转换无效。”

int genreId = 0;
. . .
genreId = GetGenreIdForGenre(_genre);

失败时“_genre”的值为“Adventure”。对 GetGenreIdForGenre() 的调用应返回“1”:

enter image description here

这是 GetGenreIdForGenre() 中失败的行:

return (int)command.ExecuteScalar();

在上下文中,GetGenreIdForGenre() 方法是:

private int GetGenreIdForGenre(string genre)
{
try
{
string qry = "SELECT GenreId FROM dbo.GENRES WHERE Genre = @genre";
using (SqlConnection connection = new SqlConnection(_connectionString))
{
using (SqlCommand command = new SqlCommand(qry, connection))
{
command.Parameters.AddWithValue("@genre", genre);
connection.Open();
return (int)command.ExecuteScalar();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return 0;
}
}

没有可用的 (TinyInt) 转换。 Int32也失败了。我需要做什么才能检索 TinyInt 值?

最佳答案

command.ExecuteScalar 的返回类型是 object,因此它返回的值是装箱的字节。在将其转换为 int 之前,您必须先对 byte 进行拆箱:

return (byte)reader.ExecuteScalar();

拆箱强制转换为byte后,它将使用可用的隐式转换为int(以匹配方法的返回类型),因此您不需要再次强制转换。

关于c# - 如何从 SQL Server 表中转换 TinyInt 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64014579/

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