2016-07-27 75 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)