保存或更新数据库中的图像(如果存在)

时间:2014-02-11 16:09:13

标签: c# asp.net sql-server

我有将代码保存到SQL Server数据库的代码,但它不起作用。

  c.cmd = c.cn.CreateCommand();
                c.cmd.CommandText = "uploadImage";

                if (c.cn.State == System.Data.ConnectionState.Closed)
                {
                    c.cn.Open();
                }
                c.cmd.Parameters.Add("@ppr", SqlDbType.Int);
                c.cmd.Parameters.Add("@imagename", SqlDbType.VarChar);
                c.cmd.Parameters.Add("@imagecontent", SqlDbType.VarChar);
                c.cmd.Parameters.Add("@imagebinary", SqlDbType.Image); 
                c.cmd.Parameters.Add("@TypeOperation", SqlDbType.Int);

                c.cmd.Parameters["@ppr"].Value = Session["Code"];
                c.cmd.Parameters["@imagename"].Value = ImageUpload.FileName;
                c.cmd.Parameters["@imagecontent"].Value = ImageUpload.PostedFile.ContentType;
                c.cmd.Parameters["@imagebinary"].Value = ImageUpload.FileBytes;
                c.cmd.Parameters["@TypeOperation"].Value = 0;

                c.cmd.ExecuteNonQuery();
                Response.Write("Yosh!!!!!!!!!!");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                if (c.cn.State == System.Data.ConnectionState.Open)
                {
                    c.cn.Close();
                }
            }

这是我的存储过程:

ALTER proc [dbo].[uploadImage] 
   @ppr int ,
   @imagename varchar ,
   @imagecontent varchar,
   @imagebinary image,
   @TypeOperation nvarchar(1)
as
   if(@TypeOperation = '0')
      begin tran

   if exists ( select PPR from ImageStorage where PPR = @ppr)
   begin 
      --select ImageBinary from [ImageStorage] where ImageID = ( select codeimg from Agent where PPR=@ppr) 
      update ImageStorage 
      set ImageName = @imagename, 
          ImageContentType = @imagecontent, 
          ImageBinary = @imagecontent  
      where   
          PPR = @ppr
   end 
   else 
       insert into ImageStorage (PPR, ImageName , ImageContentType, ImageBinary) 
       values (@ppr, @imagename, @imagecontent, @imagebinary) 
   commit 

我不知道这段代码是否正确。

我的C#代码显示错误:

  

过程或函数uploadImage'需要参数'@ppr',但未提供。

1 个答案:

答案 0 :(得分:1)

你应该在创建cmd后添加它:

   c.cmd.CommandType=CommandType.StoredProcedure;