当我从数据库检索数据时,出现以下错误“无法将类型为"System.String"的对象转换为类型为"System.Byte []"." [英] when i am retriving data from database i am getting following error "Unable to cast object of type 'System.String' to type 'System.Byte[]'."

查看:64
本文介绍了当我从数据库检索数据时,出现以下错误“无法将类型为"System.String"的对象转换为类型为"System.Byte []"."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SqlConnection connection = new SqlConnection("data source=.; initial catalog=jai; uid=sa; pwd=12345");
        string sql = "SELECT ProductName, ProductImage FROM image WHERE ImageID = @ImageID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ImageID", theID);
        connection.Open();
        object theImg = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])theImg);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }

推荐答案

检查文档中的ExecuteScalar():

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx [ ^ ]

执行查询,并返回查询返回的结果集中第一行的第一列.其他列或行将被忽略"

您的查询是:

Check the documentation for ExecuteScalar():

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx[^]

"Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored"

Your query is:

string sql = "SELECT ProductName, ProductImage FROM image WHERE ImageID = @ImageID";



这意味着您正在尝试将ProductName强制转换为byte[]

可以将查询修改为:



Which means you''re trying to cast ProductName to a byte[]

Either amend your query to:

string sql = "SELECT ProductImage FROM image WHERE ImageID = @ImageID";



或者,如果您需要返回的不仅是ProductImage列,还可以考虑使用像ADO.net DataSet或Entity Framework模型之类的ORM.



or think about using an ORM like an ADO.net DataSet or Entity Framework model if you need to return more than just the ProductImage column.


^ ]


这篇关于当我从数据库检索数据时,出现以下错误“无法将类型为"System.String"的对象转换为类型为"System.Byte []"."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆