2012-09-10 46 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已經指定如何分配的值作爲字節數組,在第二行 並傳遞作爲中的常規方式值