通过C#中调用的存储过程将Bytearray插入SQL

首先,我尝试了一切,并且无法理解为什么它不能正确更新我的varbinary字段。

在1728字节中,只有字节数组中的最后一个字节保存到字段中…

我生成我的字节数组如下:

public static byte[] StringToByteArray(String hex) { int NumberChars = hex.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes; } 

我也试过以下一个:

 public static byte[] ParseHex(string hex) { int offset = hex.StartsWith("0x") ? 2 : 0; if ((hex.Length % 2) != 0) { throw new ArgumentException("Invalid length: " + hex.Length); } byte[] ret = new byte[(hex.Length - offset) / 2]; for (int i = 0; i < ret.Length; i++) { ret[i] = (byte)((ParseNybble(hex[offset]) <= '0' && c = 'A' && c = 'a' && c <= 'f') { return c - 'a' + 10; } throw new ArgumentException("Invalid hex digit: " + c); } 

我保存数据的c#代码如下:

 using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_Conn"].ConnectionString)) { byte[] to_store = StringToByteArray(inventory); //State the Stored Proc and add Values to 'cmd' to pass to the Stored Proc SqlCommand cmd = new SqlCommand("_USP_store", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@A", TB_A.Text); cmd.Parameters.Add("@B", SqlDbType.VarBinary, 1728).Value = to_store; try { // Open Connection and execute Stored Proc conn.Open(); cmd.ExecuteNonQuery(); C2_Wipe_Message.Text = "Storing success"; C2_Wipe_Message.ForeColor = Color.FromArgb(0, 0, 255, 0); } catch { C2_Wipe_Message.Text = "An error occured.."; C2_Wipe_Message.ForeColor = Color.FromArgb(0, 255, 0, 0); } finally { if (conn.State == System.Data.ConnectionState.Open) { //Close connection IF open conn.Close(); } } } 

我把它作为一个字符串发送,我把它作为普通二进制发送,我把它作为hex字节数组发送,等等。

我的假设是在sql中使用while循环来存储它,但这并不能解释为什么总是保存最后一个字节而不是字节数组的第一个字节,请赐教,因为这是令人生气的..

* SQL SP

 @A varchar(10), @B varbinary(1728) AS UPDATE Invenotry SET A = @B WHERE (Name = @A) 

你的sql应该是这样的:

 UPDATE Invenotry SET B = @B WHERE A = @A 

您还可以尝试参数构造函数的完整版本:

 SqlParamter param = new SqlParameter("@B", SqlDbType.VarBinary, 1728, ParameterDirection.Input, // we have these parameters but they are ignored for input types false, 0, 0, null, DataRowVersion.Current, // the data to_store); cmd.Parameters.Add(param);