2

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)
    {
        generateTDES();
        SqlConnection conn = new SqlConnection(connStr);
        conn.Open();
        sql = "Insert into MembersTable (GUID,Name,Pass,CryptKey)"
        + "VALUES('" + _GUID + "','" + _Name + "','" + _Pass + "','" +key + "');";
        SqlCommand cmdIns = new SqlCommand(sql, conn);
        cmdIns.ExecuteNonQuery();
        conn.Close();
    }

2 Answers 2

3

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;

    cmdIns.Parameters.Add(_guidParam);

    // Repeat for other parameters, specifying the appropriate types

    cmdIns.ExecuteNonQuery();
Sign up to request clarification or add additional context in comments.

3 Comments

True! But is there a type that can handle varbinary?
There's also an overload on the constructor where you can specify a field length; for example, new SqlParameter("@name", DbType.NVarChar, 128);
The type you want for a varbinary is, appropriately enough, "DbType.VarBinary". In order to support more than 8000 bytes you have to explicitly specify the type as I did above.
-1

Prepare a hex string from the binary value and use it in the query for concatenation. a hex string will look like 0x123456789ABCDEF

Your final code will be like,

hexStr = "0x1234FFCD5";
sql = "Insert into MembersTable
(GUID,Name,Pass,CryptKey)"
         + "VALUES('" + _GUID + "','" + _Name + "','" + _Pass + "','"
+ hexStr + "');";

Check the code for constructing hex from binary here

For Each bytTemp As Byte In bytAllBytes
  'For your exact requirements
  strHex &= bytTemp.ToString("X2") & " "
  'however, you can use "X4" or "Xn" where replacing "n" with a numeric value will pad that number of zeros in the begining
Next

Sorry, I speak VB... :)

1 Comment

This may work, but you're much better off parametrizing the query instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.