简体   繁体   中英

Save image to SQL Server database using stored procedure

I use this code for saving an image in database. The code runs without any error but does not save data in my database:

    var db = new AlmostafaDataLinqDataContext();
    FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
    byte[] data = new byte[fs.Length];
    fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
    fs.Close();
    db.pEditImage(RecordID, data);

and this is my stored procedure:

CREATE PROCEDURE dbo.pEditImage 
    @ID int, @Image image
AS
    UPDATE Reshteh_Data 
    SET Meyvast_image = @Image
    WHERE ID = @ID

    RETURN

MY Data Base Table :

CREATE TABLE [dbo].[Reshteh_Data] (
    [ID]            INT            IDENTITY (1, 1) NOT NULL,
    [ReshtehName]   NVARCHAR (255) NOT NULL,
    [Maghta]        NVARCHAR (255) NOT NULL,
    [MA_Date]       NVARCHAR (255) NULL,
    [MV_Date]       NVARCHAR (50)  NULL,
    [Country]       NVARCHAR (255) NOT NULL,
    [M_Country]     NVARCHAR (255) NULL,
    [Meyvast_image] IMAGE          NOT NULL,
    PRIMARY KEY CLUSTERED ([ID] ASC)
);

You never handled IDisposible correctly, did not save your changes and using a file stream is needlessly complex. Try this:

using(var db = new AlmostafaDataLinqDataContext())
{
    byte[] data = System.IO.File.ReadAllBytes(FilePath);
    db.pEditImage(RecordID, data);
    db.SubmitChanges();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM