c# - 如何将 byte[] 从 C# 作为字符串传递给 SQL Server 存储过程并转换为 varbinary(MAX)

标签 c# sql-server stored-procedures varbinary

在这个项目中,有一个包装 ADO.NET 的类用于常见数据访问,如 ExecuteDataReader , ExecuteScalar等..

当使用这些方法调用存储过程时,它允许您传递 Dictionary<string, string>参数(字符串键,字符串值),然后添加到 SqlCommand对象为 SqlParameter .

有一种情况,我们必须在数据库中保存一个文档。该文档是 byte[]数据库中对应的列是varbinary(MAX) .

我们四处寻找解决方案,但所有可用的都是使用 SqlDbType.Varbinary 的示例,在这种情况下这不是一个选项。

我们最近的尝试是尝试转换 byte[]为二进制字符串,将其作为 nvarchar(max) 传递到存储过程中, 然后使用 CONVERT(varbinary(max), @theFileBinaryString)将其保存到 Document 时表,但是,这会保存损坏的文件。

C#

byte[] pDocumentBytes = ...;
string documentAsBinary = "0x" + BitConverter.ToString(pDocumentBytes).Replace("-", ""); 

SQL

@DocumentContentAsBinary nvarchar(max) -- This is "documentAsBinary" from C# above

DECLARE @DocumentContentVarbinary varbinary(max);
SET @DocumentContentVarbinary = CONVERT(varbinary(max), @DocumentContentAsBinary);

最佳答案

假设你有这个 SP:

DECLARE
@Value1 ...
@Value2 ...
...
@File VARBINARY(MAX)

INSERT INTO [YourTable] (Column1, Column2, ..., File) VALUES (@Value1, @Value2, ..., @File)

使用此语法将文件转换为字节数组并直接将字节数组作为 varbinary 数据插入:

using System.Data.SqlClient;
using System.IO;

byte[] data;

using (FileStream fs = new FileStream(document, FileMode.Open)
{
    BinaryReader fileReader = new BinaryReader(document);
    data = fileReader.ReadBytes((int)document.Length);
    document.Close(); // don't forget to close file stream
}

using (var connection = new SqlConnection("YourConnectionStringHere"))
{
    connection.Open();
    using (var command = new SqlCommand("YourSPHere", connection)
    {
        command.CommandType = CommandType.StoredProcedure;

        // insert parameters here

        // add file parameter at the end of collection parameters
        // -1 means max
        command.Parameters.AddWithValue("@File", SqlDbType.VarBinary, -1).Value = data;
        command.ExecuteNonQuery();
    }
    connection.Close();
}

引用:http://www.codeproject.com/Questions/309795/How-to-insert-byte-array-into-SQL-table

我希望这个解决方案有用。

关于c# - 如何将 byte[] 从 C# 作为字符串传递给 SQL Server 存储过程并转换为 varbinary(MAX),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37472223/

相关文章:

c# - 双击打开文件c#

c# - 在 Entity Framework 中映射自定义数据库值函数

sql-server - 将浮点型转换为日期时间时出错

c# - 通过在文本框中输入进行过滤

c# - 首先在 Entity Framework 代码中使用搜索字符串搜索 DateTime

c# - 使用 PInvoke 与 .NET 提供的函数

c# - 默认文件名 SaveFileDialog

mysql - 存储过程和外键检查

mysql - mysql存储函数中的未知列错误

mysql - 如何在存储过程中创建变量游标?