簡體   English   中英

如何將C#中的byte []作為字符串傳遞到SQL Server存儲過程並轉換為varbinary(MAX)

[英]How to pass byte[] from C# as string to SQL Server stored procedure and convert into varbinary(MAX)

在此項目中,有一個包裝ADO.NET的類,用於執行ExecuteDataReaderExecuteScalar等常見數據訪問。

使用這些方法調用存儲過程時,它允許您傳遞Dictionary<string, string>參數(字符串鍵,字符串值),然后將它們作為SqlParameter添加到SqlCommand對象。

在某些情況下,我們必須將文檔保存在數據庫中。 該文檔是一個byte[] ,數據庫中的相應列是varbinary(MAX)

我們一直在尋找解決方案,但是可用的只是使用SqlDbType.Varbinary示例,在這種情況下,這不是一個選擇。

我們的最新嘗試是嘗試將byte[]轉換為二進制字符串,將其作為nvarchar(max)傳遞到存儲過程中,然后在將其保存到Document表時使用CONVERT(varbinary(max), @theFileBinaryString) ,但是,這會保存損壞的文件。

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
        command.Parameters.AddWithValue("@File", SqlDbType.VarBinary).Value = data;
        command.ExecuteNonQuery();
    }
    connection.Close();
}

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

我希望此解決方案有用。

更新查詢以使用參數,並將字節數組作為參數直接傳遞給表

例如SQL:

insert into table values (@data);

C#

SqlComman com = new SqlCommand("insert into table values (@data);",Database Connection);
com.Paramaters.Add(new SqlParameter("@Data" Byte array));
com.executeNonQuery();

沒有SqlDbType可以在VARBINARY(MAX)byte[]之間正確映射。 但這實際上是可以的,因為參數化基礎結構只為您處理此問題,所以下面的代碼將起作用:

var binary = new bytes[1];
var command = new SqlCommand("INSERT INTO [MyTable]([BinaryColumn]) VALUES (@binary)");
command.Parameters.AddWithValue("@binary", binary);
command.ExecuteNonQuery();

有關更多詳細信息,請參見此處: 什么SqlDbType映射到varBinary(max)?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM