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

标签 c# sql-server-express data-conversion tinyint

我有这个 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/

相关文章:

c# - 每个应用程序部署都有唯一的 'code'

sql-server - sql server 2005 express .mdf + .ldf 的最大限制是 4 GB 还是仅适用于 .mdf?

c# - 错误 : 50 - Local Database Runtime error occurred, 但如果我发布该项目,它可以正常工作

java - 将2个字符串转换为2个数组,结果为奇数和偶数,数字在java 7中

c# - (等待)任务,并非所有代码路径都返回一个值

c# - DirectoryEntries.查找 : "An invalid dn syntax has been specified"

c# - Unity:带有PlayScheduled()的准确节拍器不起作用

docker - SQL Server Express 无法在运行 docker 容器 (Windows) 时启动

python - 如何在 Python 中将人类可读的日期和时间转换为 Unix 时间戳?

c# - 自动映射器从字符串转换为 Int