2016-07-27 68 views
0

我構建sql_insert_stringMicrosoft.ApplicationBlocks.Data.SqlHelper被用來作爲如下:插入字節數組到SQL Server

SqlHelper.ExecuteNonQuery(Transaction, CommandType.Text, sql_insert_string) 

當我將鼠標懸停在SQL語句,它看起來象下面這樣:

string sql_insert_string = "Insert into images_table(image_id,  image_byte_array) values ('123', System.Byte[]) 

其中一個插入值是如上所示的一個字節數組。該變量在字節數組中有值,比如byte [6738]。但在構建sql_insert_string之後,它的值爲System.Byte[]image_byte_array列的類型是varbinary(max)。該數據庫是因爲這樣的SQL Server 2008數據庫引發以下錯誤:

An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as \"\" or [] are not allowed. Change the alias to a valid name.

+0

您的sql字符串生成器只是在您的'byte []'類型的變量上調用'ToString()'。顯示創建sql查詢字符串的方法 – Fabio

+3

您不應該*構建* SQL語句 - 您應該使用**參數**來避免SQL注入攻擊! –

+1

'SqlParameter'不僅可以節省您從SQL注入,此外你不會有這樣的問題,因爲所有的輸入值將被正確地「轉換」爲SqlParameters – Fabio

回答

2

可以插入像這樣的字節數組:

 private void FireSql(byte[] input) 
     { 
      const string sql_insert_string = 
       "Insert into images_table(image_id, image_byte_array) values (@image_id, @image_byte_array)"; 

      SqlTransaction transaction = null; //wherever you get the transaction obj from. 

      var imageIdParam = new SqlParameter("@image_id", SqlDbType.Int, 4) 
      { 
       Direction = ParameterDirection.Input, 
       Value = 123 
      }; //change the data type to whatever data type you are expecting 

      var byteParam = new SqlParameter("@image_byte_array", SqlDbType.VarBinary) 
      { 
       Direction = ParameterDirection.Input, 
       Size = input.Length, 
       Value = input 
      }; //change the data type to whatever data type you are expecting 

      SqlHelper.ExecuteNonQuery(transaction, CommandType.Text, sql_insert_string, imageIdParam, byteParam); 
     } 

我建議尋找一個ORM(https://en.wikipedia.org/wiki/Object-relational_mapping)像實體框架(http://www.asp.net/entity-framework)做這一切爲你而過多增加安全性和未來的變化更輕鬆。

0

您可以使用

string sql_insert_string = 
    String.Format("INSERT INTO images_table(image_id, image_byte_array) VALUES ('123', CAST('{0}' AS VARBINARY(MAX)))", System.Byte[].ToString()); 

是的,正如@marc_s評論說,你不應該構建SQL語句作爲安全問題。

0

你應該使用參數在構造SQL查詢,這顯然會避免SQL注入攻擊。您的查詢如何構建仍然不清楚。 像這樣的東西應該爲你做。

SqlParameter sParam = new SqlParameter("@image_byte_array", SqlDbType.VarBinary) 
{ 
Value = image 
}; 
SqlHelper.ExecuteNonQuery(Transaction, CommandType.Text, sql_insert_string, sParam)