将图片添加到员工档案

时间:2015-10-07 06:22:43

标签: c# sql-server-2008

我有一个员工资料表,并希望将员工图片添加为varbinary(max)

如何使用C#和Ms SQL Server 2008使用Winform加载/保存图像。

1 个答案:

答案 0 :(得分:0)

保存图像

byte[] data = System.IO.File.ReadAllBytes(filePath);
using(SqlCommand cm = new SqlCommand("SaveImage", connection, transaction))
{
   cm.CommandType = CommandType.StoredProcedure;
   cm.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int,0, ParameterDirection.InputOutput, false, 10, 0, "Id", DataRowVersion.Current, (SqlInt32)instance.Id));
   cm.Parameters.Add(new SqlParameter("@Title", SqlDbType.NVarChar,50, ParameterDirection.Input, false, 0, 0, "Title", DataRowVersion.Current, (SqlString)instance.Title));
   if (instance.Data.Length > 0)
   {
       cm.Parameters.Add(new SqlParameter("@Data", SqlDbType.VarBinary,instance.Data.Length, ParameterDirection.Input, false, 0, 0, "Data", DataRowVersion.Current, (SqlBinary)instance.Data));
   }
   else
   {
       cm.Parameters.Add(new SqlParameter("@Data", SqlDbType.VarBinary,0, ParameterDirection.Input, false, 0, 0, "Data", DataRowVersion.Current, DBNull.Value));                    
   }
   cm.ExecuteNonQuery();
}

创建存储过程

CREATE PROCEDURE SaveImage
(
@Id int OUTPUT 
,@Title nvarchar(50)
,@Data varbinary(MAX)
)
AS
SET NOCOUNT ON
SET XACT_ABORT ON

IF @Id IS NULL OR @Id <= 0
BEGIN
SELECT @Id = ISNULL(MAX([Id]),0) + 1 FROM [dbo].[Images]
END

INSERT INTO [dbo].[Images] (
[Id]
,[Title]
,[Data]
) VALUES (
@Id
,@Title
,@Data
)

读取Varbinary数据

private static byte[] getImage(int EmployeeId)
{
    using (SqlConnection cn = new SqlConnection("..."))
    using (SqlCommand cm = cn.CreateCommand())
    {
        cm.CommandText = @"
            SELECT ImageData
            FROM   EmployeeTable
            WHERE  EmployeeId = @Id";
        cm.Parameters.AddWithValue("@Id", EmployeeId);
        cn.Open();
        return cm.ExecuteScalar() as byte[];
    }
}

byte[] data = getImage("EmployeeID");
MemoryStream ms = new MemoryStream(data);
EmployeeImage.Image = Image.FromStream(ms);