C# 使用C将PDF作为字节数组插入SQL Server存储过程#
我有一个PDF文件,需要插入SQL Server表的C# 使用C将PDF作为字节数组插入SQL Server存储过程#,c#,sql,sql-server,stored-procedures,C#,Sql,Sql Server,Stored Procedures,我有一个PDF文件,需要插入SQL Server表的varbinary列中 我使用C将PDF转换为字节数组# 我向SqlCommand添加了一个参数: SqlParameter fileP = new SqlParameter("@file", SqlDbType.VarBinary); fileP.Value = bytes; myCommand.Parameters.Add(fileP); 存储过程基本上采用varbinary参数,并将其插入表的varbinary列中 create
varbinary
列中
我使用C将PDF转换为字节数组#
我向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 ...
我在执行此过程时出错
在SQLServer探查器中,我发现执行以下过程
exec pdfInsert @file = 0x2555... <-- byte array of pdf
我得到一个错误:
不允许从数据类型varchar(max)隐式转换为varbinary(max)。使用CONVERT函数运行此查询
只是想知道我做错了什么?非常感谢您的帮助。谢谢此代码适用于我:
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?尝试使用而不是“SqlParameter fileP=newsqlparameter(@file),SqlDbType.VarBinary);”
使用此cm.Parameters.AddWithValue(“@file”,字节)
还要确保列类型为varbinary(max),而不是任何其他数据类型是表varChar(max)中的数据类型,而不是varbinary(max)?@Decker97其varbinary(max)。谢谢@Decker97。我有同样的代码。发现字节数组(SSMS放置的)中的新行字符创建了错误。整个bytearray应该在一行中,并且过程执行正确。无论如何谢谢你的帮助!!
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 )