如何将Byte []插入SQL Server VARBINARY列 [英] How Do I Insert a Byte[] Into an SQL Server VARBINARY Column
本文介绍了如何将Byte []插入SQL Server VARBINARY列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面有一个突出显示的字节数组,如何将其插入SQL Server数据库的Varbinary列?
I have a byte array highlighted below, how do I insert it into a SQL Server database Varbinary column?
byte[] arraytoinsert = new byte[10]{0,1,2,3,4,5,6,7,8,9};
string sql =
string.format
(
"INSERT INTO mssqltable (varbinarycolumn) VALUES ({0});",WHATTODOHERE
);
推荐答案
我的解决方案是使用参数化查询,因为连接对象负责正确格式化数据(包括确保数据类型正确,并转义危险"字符)
My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):
// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
// Replace 8000, below, with the correct size of the field
cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
cmd.ExecuteNonQuery();
}
按照约翰·桑德斯的建议添加了包装的使用"语句,以在完成后正确处置SqlCommand.
Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with
这篇关于如何将Byte []插入SQL Server VARBINARY列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文