mitsu
mitsu

Reputation: 430

Save or update image (if it exists) in database

I have code that saves images to a SQL Server database, but it doesn't work.

  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();
                }
            }

This is my stored procedure :

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 

I don't know if this code is correct.

My C# code displays an error:

The procedure or function uploadImage 'expects parameter '@ppr', which was not provided.

Upvotes: 0

Views: 72

Answers (1)

Mostafa Soghandi
Mostafa Soghandi

Reputation: 1594

you should add this after cmd creation:

   c.cmd.CommandType=CommandType.StoredProcedure;

Upvotes: 1

Related Questions