Reputation:
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();
}
Upvotes: 2
Views: 5933
Reputation: 11759
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();
Upvotes: 3
Reputation: 5453
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... :)
Upvotes: -1