如何使用c#将字符串存储在varbinary(max)列中

Rag*_*ock 8 c# sql sql-server

如何将字符串存储在varbinary(max)列中?

我在转换过程中遇到麻烦我正在这样做:

    cmd.CommandText = "Insert into " + bdcombo.Text + ".dbo.nomes (id, nome) values (@id, @nome)";
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlcon;

    cmd.Parameters.Add("@nome", SqlDbType.VarBinary, 20).Value = Convert.ToSByte(textBox1.Text);
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 16

如果要存储字符串,请使用[n] varchar(max).

如果必须使用varbinary(max),那么要获取字节,必须使用编码,例如:

byte[] theBytes = Encoding.UTF8.GetBytes(theString);
Run Code Online (Sandbox Code Playgroud)

然后:

string theString = Encoding.UTF8.GetString(theBytes);
Run Code Online (Sandbox Code Playgroud)

(阅读时)