c# – 如何将图像存储到varbinary(max)列?
发布时间:2020-12-15 18:24:23 所属栏目:百科 来源:网络整理
导读:我在将一个 Image插入sql server 2008时遇到了这个以下的SQL异常. Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query 在数据库中,Image列的数据类型是Varbinary(MAX). 编辑 代码
|
我在将一个
Image插入sql server 2008时遇到了这个以下的SQL异常.
在数据库中,Image列的数据类型是Varbinary(MAX). 编辑 代码解除了评论 paramaters.Add(getParam("@imageFilePath",DbType.AnsiString,imageFilePath));
解决方法
使用它将文件读入字节数组:
// Old fashioned way
public static byte[] ReadFile(string filePath)
{
byte[] buffer;
FileStream fileStream = new FileStream(filePath,FileMode.Open,FileAccess.Read);
try
{
int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read
// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer,sum,length - sum)) > 0)
sum += count; // sum is a buffer offset for next reading
}
finally
{
fileStream.Close();
}
return buffer;
}
要么 // Thanks Magnus!
byte[] data = System.IO.File.ReadAllBytes(filePath);
然后使用此保存图像数据(我使用的图像类“实例”包含我在instance.Data中的图像信息和字节数组): using(SqlCommand cm = new SqlCommand("SaveImage",connection,transaction)){
cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.Add(new SqlParameter("@Id",SqlDbType.Int,ParameterDirection.InputOutput,false,10,"Id",DataRowVersion.Current,(SqlInt32)instance.Id));
cm.Parameters.Add(new SqlParameter("@Title",SqlDbType.NVarChar,50,ParameterDirection.Input,"Title",(SqlString)instance.Title));
if (instance.Data.Length > 0)
{
cm.Parameters.Add(new SqlParameter("@Data",SqlDbType.VarBinary,instance.Data.Length,"Data",(SqlBinary)instance.Data));
}
else
{
cm.Parameters.Add(new SqlParameter("@Data",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 ) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
