gpt4 book ai didi

c# - 如何将图像存储到 varbinary(max) 列?

转载 作者:太空狗 更新时间:2023-10-29 20:49:33 24 4
gpt4 key购买 nike

我在将图像插入 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)。

编辑

代码从评论中提取

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,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
)

关于c# - 如何将图像存储到 varbinary(max) 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7324190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com