如何将Byte []转换为数据以在SQL Server的varbinary(max)列中插入值?

如何将Byte []转换为数据以在SQL Server的varbinary(max)列中插入值?

问题描述:

我有一个具有 byte [] 属性的对象,我想将此值转换为正确的值,以便可以使用T-SQL将其插入数据库中。

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-的正确值。

But I don't know how I could convert the byte[] to the correct value for T-SQL for the insert.

谢谢。

创建控制台应用项目并尝试使用此代码

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();
        }
    }
}