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 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 Byte[] 插入 SQL Server VARBINARY 列


基础教程推荐
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01