如何将字节[]插入SQL Server VARBINARY列

div*_*nci 61 sql-server arrays

我在下面突出显示了一个字节数组,如何将其插入SQL Server数据库Varbinary列?

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
    );
Run Code Online (Sandbox Code Playgroud)

先谢谢你们!

Dav*_*d M 79

试试这个:

"0x" + BitConverter.ToString(arraytoinsert).Replace("-", "")
Run Code Online (Sandbox Code Playgroud)

虽然你应该真的使用参数化查询而不是字符串连接当然...

  • @peSHIr:-1为谁?我所做的只是回答被问到的问题...... (6认同)
  • 最后回答这个问题而不是'你应该使用参数..'有理由不使用参数 - 例如在单个查询中超过2,100个参数. (5认同)
  • 这里最小,但参数化查询可以编译然后缓存,从而节省了每个后续查询的编译成本.它们还可以防止SQL注入攻击.最后,您可以直接将参数的值设置为字节数组,并避免使用BitConverter ... (4认同)

Jas*_*ove 71

我的解决方案是使用参数化查询,因为连接对象负责正确格式化数据(包括确保正确的数据类型,并在适用的情况下转义"危险"字符):

// 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();
}
Run Code Online (Sandbox Code Playgroud)

编辑:添加了John Saunders建议的包装"using"语句,以便在完成后正确处理SqlCommand

  • 如果列是VARBINARY(MAX),则将8000替换为-1,请参阅http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/e61f0616-0866-4f3f-aeba-6a76e144e169/ (13认同)
  • 杰森,你能不能在"SqlCommand cmd = new ..."周围加上一个使用声明?否则,我觉得有义务投票,我讨厌这个. (3认同)