如何将Byte []转换为sql图像

时间:2009-07-27 10:18:37

标签: .net asp.net

我有sql数据类型图像来存储webparts的状态,但在.Net中它是Byte []。如何将Byte []转换为sql图像以进行插入和其他操作。

2 个答案:

答案 0 :(得分:11)

只需将Binary指定为参数类型,它的值可以是byte[]

byte[] data; // wherever this comes from

using (SqlCommand command = new SqlCommand())
{
    command.Connection = connection;
    command.CommandText = "INSERT INTO BinaryTable (BinaryData) VALUES (@BinaryData)";

    SqlParameter param = new SqlParameter("@BinaryData", SqlDbType.Binary);
    param.Value = data;

    command.Parameters.Add(param);
    command.ExecuteNonQuery();
}

编辑另外值得注意的是,如果您使用的是SQL Server 2005/2008,那么您应该使用VARBINARY(MAX)而不是IMAGE,因为后者已弃用。< / p>

答案 1 :(得分:0)

这是一个示例函数

public bool AddCompanyIcon(string MakeName, byte[] BytesOriginal,string ImageName)
    {
        try
        {
            System.Data.SqlClient.SqlParameter[] ImgPara = new SqlParameter[3];
            ImgPara[0] = new SqlParameter("@MakeName", MakeName);
            ImgPara[1] = new SqlParameter("@MakeIcon", BytesOriginal);
            ImgPara[2] = new SqlParameter("@ImageName", ImageName);

            db.ExecuteScalerSP("sp_AddAutoCompanyLogo", ImgPara);
            db.CloseConnection();
            return true;
        }
        catch 
        {
            return false;
        }
    }

以下是sp_AddAutoCompanyLogo存储过程

ALTER PROCEDURE [dbo].[sp_AddAutoCompanyLogo] 
    -- Add the parameters for the stored procedure here
    @MakeName varchar(50),
    @MakeIcon image,
    @ImageName varchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    -- Insert statements for procedure here
    insert into IVAutoGalleryLogos(MakeName,MakeIcon,ImageName) 
    values(upper(@MakeName),@MakeIcon,@ImageName)
END

希望这会有所帮助......