如何将 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
相关文章