Sql – How to insert byte array into SQL table


I try insert byte array in sql table, data type in table is VarBinary(Max), but it finish with this error:

System.Data.SqlClient.SqlException: Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.

Any adice, I am beginner with Sql…

Here is my code:

   byte[] key;
   byte[] iv;

   void generateTDES()
       TripleDESCryptoServiceProvider tdes;
       tdes = new TripleDESCryptoServiceProvider();
       tdes.KeySize = 128;
       key = tdes.Key;
       iv = tdes.IV;

    public void WriteUser(string _GUID, string _Name, string _Pass)
        SqlConnection conn = new SqlConnection(connStr);
        sql = "Insert into MembersTable (GUID,Name,Pass,CryptKey)"
        + "VALUES('" + _GUID + "','" + _Name + "','" + _Pass + "','" +key + "');";
        SqlCommand cmdIns = new SqlCommand(sql, conn);

Best Solution

You will maintain more control over the types, protect yourself from injection attacks, and enjoy slightly better performace by parameterizing your query as follows:

    sql = "Insert into MembersTable (GUID,Name,Pass,CryptKey)"
    + "VALUES(@guid, @name, @pass, @key);";

    SqlCommand cmdIns = new SqlCommand(sql, conn);

    SqlParameter _guidParam = new SqlParameter("@guid", DbType.UniqueIdentifier);
    _guidParam.Value = _GUID;


    // Repeat for other parameters, specifying the appropriate types