[英]How convert a Byte[] to a data to insert a value in a varbinary(max) column in SQL Server?
I have a object with a byte[]
property, and I would like to convert this value to the correct value to can insert it into the database using T-SQL.我有一个带有
byte[]
属性的对象,我想将此值转换为正确的值,以便可以使用 T-SQL 将其插入到数据库中。
But I don't know how I could convert the byte[]
to the correct value for T-SQL for the insert.但我不知道如何将
byte[]
转换为插入的 T-SQL 的正确值。
Thanks.谢谢。
You want to convert to VarBinary . 您想要转换为VarBinary 。
See the following: 请参阅以下内容:
SQL Server Data Type Mappings SQL Server数据类型映射
simple example (setting command parameter) 简单示例(设置命令参数)
byte[] data;
command.Parameters.Add("@data", SqlDbType.VarBinary).Value = data;
T-SQL example of how to pass in varbinary 如何传入varbinary的T-SQL示例
CREATE PROCEDURE YourStoredProc
@data varbinary(max)
AS
BEGIN
-- your code
END
Create a Console Application project and try this code 创建一个控制台应用程序项目并尝试此代码
// Sample Class
public class MyClass
{
public byte[] data;
}
// Main
static void Main(string[] args)
{
MyClass cls = new MyClass();
using (SqlConnection cn = new SqlConnection("CONNECTION STRING"))
{
cn.Open();
using (SqlCommand cmd = new SqlCommand("insert into MyTable values (@data)", cn))
{
cmd.Parameters.AddWithValue("@data", cls.data);
cmd.ExecuteNonQuery();
}
}
}
Generating raw varbinary to insert to database (copy-paste case)生成原始 varbinary 以插入到数据库(复制粘贴案例)
string ToVarbinary(byte[] data)
{
var sb = new StringBuilder((data.Length * 2) + 2);
sb.Append("0x");
for (int i = 0; i < data.Length; i++)
{
sb.Append(data[i].ToString("X2"));
}
return sb.ToString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.