简体   繁体   English

有没有一种方法可以将C#字符串插入SQL varbinary列中?

[英]Is there a way to insert a C# string into a SQL varbinary column?

I am using SqlConnection and SqlCommand in C# to insert rows of strings (via Parameters.AddWithValue ) into SQL Server. 我在C#中使用SqlConnectionSqlCommand将字符串行(通过Parameters.AddWithValue )插入SQL Server。 One of the columns I need to insert into is a Varbinary . 我需要插入的一列是Varbinary Is there any way to do the conversion in either C# or SQL Server? 有没有办法在C#或SQL Server中进行转换?

According to this answer , you can use the CONVERT function to insert a string into a VARBINARY column. 根据此答案 ,可以使用CONVERT函数将字符串插入VARBINARY列。 Make sure you use the proper encoding, as discussed in that answer. 确保使用正确的编码,如该答案中所述。

insert Table_2 (Test) values( CONVERT(varbinary(30), N'this is a test') ) 
select * from Table_2
select CONVERT(nvarchar(30), test) from Table_2

So the C# code would look something like 所以C#代码看起来像

    // Get from config
    string connectionString = "";

    using (var conn = new SqlConnection(connectionString))
    {
        string sql = "insert Table_2 (Test) values( CONVERT(varbinary(30), @nvarcharParam) )";
        using (var cmd = new SqlCommand(sql, conn))
        {
            var param = cmd.Parameters.AddWithValue("nvarcharParam", "This is a test");
            param.DbType = DbType.String;

            cmd.ExecuteNonQuery();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM