Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store a string in a varbinary(max) column using c#

Tags:

c#

sql

sql-server

How can I store a string in a varbinary(max) column?

I'm havig trouble in the convertion process i'm doing this:

    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);
like image 426
RagnaRock Avatar asked Nov 24 '11 10:11

RagnaRock


1 Answers

If you want to store a string, use [n]varchar(max).

If you must use varbinary(max), then to get the bytes you must use an encoding, for example:

byte[] theBytes = Encoding.UTF8.GetBytes(theString);

and later:

string theString = Encoding.UTF8.GetString(theBytes);

(when reading)

like image 121
Marc Gravell Avatar answered Oct 15 '22 08:10

Marc Gravell