2012-09-10 114 views
0

我想从URL中获取一个查询字符串并将它发送到MSSQL中的存储过程。查询字符串是varbinary类型,当我尝试发送它时,我的应用程序正在抛出异常。我还想返回存储过程底部的select语句,它只是说Select 'Processed'输入到SQL存储过程

+0

它抛出什么异常? –

+0

+ \t \t ServerVersion \t“con.ServerVersion”扔“System.InvalidOperationException”类型\t字符串{} System.InvalidOperationException的一个例外 – Tim

回答

2

不得不实际创建函数来分析十六进制代码,然后将其发送到数据库

static byte[] ParseHexString(string value) 
     { 
      if (string.IsNullOrEmpty(value)) return null; 
      if (1 == (1 & value.Length)) throw new ArgumentException("Invalid length for a hex string.", "value"); 

      int startIndex = 0; 
      int length = value.Length; 
      char[] input = value.ToCharArray(); 
      if ('0' == input[0] && 'x' == input[1]) 
      { 
       if (2 == length) return null; 
       startIndex = 2; 
       length -= 2; 
      } 

      Func<char, byte> charToWord = c => 
      { 
       if ('0' <= c && c <= '9') return (byte)(c - '0'); 
       if ('A' <= c && c <= 'F') return (byte)(10 + c - 'A'); 
       if ('a' <= c && c <= 'f') return (byte)(10 + c - 'a'); 
       throw new ArgumentException("Invalid character for a hex string.", "value"); 
      }; 

      byte[] result = new byte[length >> 1]; 
      for (int index = 0, i = startIndex; index < result.Length; index++, i += 2) 
      { 
       byte w1 = charToWord(input[i]); 
       byte w2 = charToWord(input[i + 1]); 
       result[index] = (byte)((w1 << 4) + w2); 
      } 

      return result; 
     } 
0

不应该为二进制发送一个字节数组(byte[])吗?我不认为它会接受纯字符串。尝试使用System.Text.Encoding.UTF8.GetBytes方法将其转换为字节数组。

UPDATE:这个问题的答案告诉编译器使用二进制数据的一种特殊类型:What SqlDbType maps to varBinary(max)?

+0

可能你这个提供一个例子对不起新我希望我能传递价值一个字符串。不知道我怎么会为byte []编写代码感谢 – Tim

+0

我现在无法访问visual studio,所以它可能无法正常工作,但是您可以尝试:'byte [] buf = System.Text.Encoding。 UTF8Encoding.GetBytes(yourString); cmd.Parameters.Add(“@ dec”,SqlDbType.VarBinary).Value = buf;' –

+0

感谢您的回应,UTF8Encoding只能在.net 4.5下使用?似乎它不适合我。 – Tim

1

如果您想字节]类型,你可以用这个代码试试,你不通过串

cmd.Parameters.Add("@dec", SqlDbType.VarBinary).Value = ;//Relpace with your new Byte[] 

或者,如果你想字符串类型,你可以用字符串类型尝试

cmd.Parameters.Add("@dec", SqlDbType.VarChar).Value = QS;//Your string 

链接:http://msdn.microsoft.com/fr-fr/library/system.data.sqldbtype%28v=vs.80%29.aspx

+0

不知道你明白你想告诉我做 – Tim

+0

如果你想传递字符串值,请尝试:cmd.Parameters.Add( “@dec”,SqlDbType.VarChar).Value = QS。如果你想使用VarBinary传递Byte []参数 –

0

Aghilas已经指定如何分配的值作为字节数组,在第二行 并传递作为中的常规方式值