2

I have a PDF which I need to insert into a SQL Server table's varbinary column.

I convert the PDF into a byte array using C#

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

I add a parameter to the SqlCommand:

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

The stored procedure basically takes a varbinary parameter and inserts into a table's varbinary column

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

I get an error on execution of this procedure.

In the SQL Server profiler I found that the following procedure executes

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

The error is

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '40E3'.

In SSMS, when I execute this procedure with single quotes at both of the byte array.

Like this:

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

I get the error:

Implicit conversion from data type varchar(max) to varbinary(max) is not allowed. Use the CONVERT function to run this query.

Just curious to know what wrong am I doing? Any help is much appreciated. Thanks

4

2 回答 2

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 年?

于 2013-07-09T17:37:51.037 回答
0

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

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

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

于 2013-07-09T17:40:44.897 回答