我尝试在sql表中插入字节数组,表中的数据类型是VarBinary(Max),但它完成了这个错误:
System.Data.SqlClient.SqlException:不允许从数据类型varchar到varbinary(max)的隐式转换。使用CONVERT函数运行此查询。
任何adice,我是Sql初学者......
这是我的代码:
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();
}
答案 0 :(得分:3)
您将通过参数化查询来保持对类型的更多控制,保护自己免受注入攻击,并享受稍微更好的性能:
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();
答案 1 :(得分:-1)
从二进制值准备十六进制字符串,并在查询中使用它进行连接。十六进制字符串看起来像0x123456789ABCDEF
您的最终代码将是,
hexStr = "0x1234FFCD5"; sql = "Insert into MembersTable (GUID,Name,Pass,CryptKey)" + "VALUES('" + _GUID + "','" + _Name + "','" + _Pass + "','" + hexStr + "');";
检查从二进制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
对不起,我说VB ......:)