【问题标题】:Inserting PDF as byte array to SQL Server stored procedure using C#使用 C# 将 PDF 作为字节数组插入 SQL Server 存储过程
【发布时间】:2013-07-10 02:13:43
【问题描述】:

我有一个 PDF,我需要将它插入到 SQL Server 表的 varbinary 列中。

我使用 C# 将 PDF 转换为字节数组

byte[] bytes = File.ReadAllBytes(fileName);

我给SqlCommand添加了一个参数:

 SqlParameter fileP = new SqlParameter("@file", SqlDbType.VarBinary);
 fileP.Value = bytes;
 myCommand.Parameters.Add(fileP);

存储过程基本上采用varbinary 参数并插入到表的varbinary 列中

 create procedure pdfInsert 
      @file varbinary(MAX)
 as
     insert ...

执行此过程时出现错误。

在 SQL Server 探查器中,我发现执行了以下过程

exec pdfInsert @file = 0x2555... <-- byte array of pdf

错误是

消息 102,第 15 级,状态 1,第 2 行
'40E3' 附近的语法不正确。

在 SSMS 中,当我在两个字节数组中使用单引号执行此过程时。

像这样:

 exec pdfInsert @file = '0x2555.......'

我得到错误:

不允许从数据类型 varchar(max) 到 varbinary(max) 的隐式转换。使用 CONVERT 函数运行此查询。

只是想知道我做错了什么?任何帮助深表感谢。谢谢

【问题讨论】:

  • 表中的数据类型是varChar(max)而不是varbinary(MAX)?
  • @Decker97 它的 varbinary(MAX)。

标签: c# sql sql-server stored-procedures


【解决方案1】:

此代码适用于我:

private void button1_Click(object sender, EventArgs e)
{
    byte[] bytes = File.ReadAllBytes(@"C:\pdf.pdf");
    SqlParameter fileP = new SqlParameter("@file", SqlDbType.VarBinary);
    fileP.Value = bytes;
    SqlCommand myCommand = new SqlCommand();
    myCommand.Parameters.Add(fileP);
    SqlConnection conn = new SqlConnection(@"Data Source=CoastAppsDev\SQL2008;Initial Catalog=CSharpWinForms;Integrated Security=True;");
    conn.Open();
    myCommand.Connection = conn;
    myCommand.CommandText = "spPdfInsert";
    myCommand.CommandType = CommandType.StoredProcedure;
    myCommand.ExecuteNonQuery();
    conn.Close();

}

使用存储过程:

Create Procedure [dbo].[spPdfInsert] (
    @file varbinary(max) = null
)
AS


Insert Into Pdfs
(   pdfData )
Values
(   @file )

您使用的是哪个版本的 SQL Server? 2008 年?

【讨论】:

  • 谢谢@Decker97。我有同样的代码。发现字节数组(SSMS)中的换行符会产生错误。整个 bytearray 应该在 1 行中,并且过程正确执行。无论如何感谢您的帮助!
【解决方案2】:

尝试使用而不是“SqlParameter fileP = new SqlParameter("@file", SqlDbType.VarBinary);"

使用这个 cm.Parameters.AddWithValue("@file", bytes);

还要确保列类型是 varbinary(max) 而不是任何其他数据类型

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多