使用C#将PDF作为字节数组插入SQL Server存储过程

时间:2013-07-09 17:16:23

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

我有一个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

错误是

  

Msg 102,Level 15,State 1,Line 2
  '40E3'附近的语法不正确。

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

像这样:

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

我收到错误:

  

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

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

2 个答案:

答案 0 :(得分:3)

此代码适用于我:

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?

答案 1 :(得分:0)

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

使用此cm.Parameters.AddWithValue(“@ file”,bytes);

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