Adding an image to SQL database using Visual C#

前端 未结 4 1496
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 20:16

I am working on a visual C# program for image processing.I am trying to add image to sql database using Visual C# (Windows forms) and ADO.NET.

I have converted the i

相关标签:
4条回答
  • 2020-12-06 20:41

    Execute this stored procedure:

    create procedure prcInsert
    (
       @txtEmpNo varchar(6),
       @photo image
    )
    as
    begin
       insert into Emp values(@txtEmpNo, @photo)
    end
    

    Table Emp:

    create table Emp
    (
       [txtEmpNo] [varchar](6) NOT NULL,
       imPhoto image
    )
    
    0 讨论(0)
  • 2020-12-06 20:53

    Try with something like this:

    byte[] fileBytes=System.IO.File.ReadAllBytes("path to file");
    System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("insert  into table(blob,filename) values (@blob,@name)");
    command.Parameters.AddWithValue("blob", fileBytes);
    command.Parameters.AddWithValue("name", "filename");
    command.ExecuteNonQuery();
    
    0 讨论(0)
  • 2020-12-06 20:56

    The selected file stream should be converted to byte array.

            FileStream FS = new FileStream(filepath, FileMode.Open, FileAccess.Read); //create a file stream object associate to user selected file 
            byte[] img = new byte[FS.Length]; //create a byte array with size of user select file stream length
            FS.Read(img, 0, Convert.ToInt32(FS.Length));//read user selected file stream in to byte array
    

    Now this works fine. Database still shows < Binary data > but it could be converted back to image using memorystream method.

    Thanks to all...

    0 讨论(0)
  • 2020-12-06 20:59

    Assuming that you are using VARBINARY to store your image (which you should be), you may need to make your SqlParameter more strongly typed:

    So instead of

    cmd.Parameters.Add(new SqlParameter("@Imgg", image));
    

    You would use:

    cmd.Parameters.Add("@Imgg", SqlDbType.VarBinary).Value = (SqlBinary)image;
    

    You could also use System.IO.File.ReadAllBytes to shorten your code turning a file path into a byte array.

    0 讨论(0)
提交回复
热议问题