我有字符串值项:如何在SQL Server中转换为二进制后得到的字符串返回在C#
TxtProductKey.Text has value "key"
编码这个值
byte[] Key = Encoding.ASCII.GetBytes(TxtProductKey.Text.Trim());
将它保存在数据库表中的数据类型的列binary(50) null
。
下表中的值如下:
0x6B00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
现在我试图把它找回来的,我输入的字符串值Key
byte [] TempKey = (byte[])LicenseInfo.Tables[0].Rows[0]["ProductKey"];
var newText = Encoding.ASCII.GetString(TempKey);
但我在得到结果newText
是:
k\0\0\0\0\0\00\
我在哪里干什么有什么问题?我希望您的建议
C#代码在数据库中保存的值:
Sqlconnection.Open();
SqlCommand Cmd = new SqlCommand("SpAddAttempts", Sqlconnection);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("@Attempts", SqlDbType.Int).Value = Attempt;
Cmd.Parameters.Add("@Activate", SqlDbType.Bit).Value = Activate;
Cmd.Parameters.Add("@Key", SqlDbType.Binary).Value = Key;
Cmd.ExecuteNonQuery();
CloseConnection();
存储过程:
ALTER PROCEDURE [dbo].[SpAddAttempts]
@Attempts INT,
@Activate BIT,
@Key BINARY
AS
BEGIN
UPDATE License
SET Attempts = @Attempts,
Activate = @Activate,
ProductKey = @Key
WHERE LicenseId = '1'
END
您没有保存它是正确的。数据只有一个非零字节,它应该有三个字节(即'0x6B657900 ...') – dasblinkenlight
你可以这样做,你可以在调试中看到关键字节数组的值是什么?它进入数据库之前。这个例子只显示了db二进制数据中的一个字符 – farbiondriven
@dasblinkenlight你能告诉我错误吗?我的保存代码在我的文章中。 – john