[英]Inserting byte array into SQL Server
我正在构造要在Microsoft.ApplicationBlocks.Data.SqlHelper
中使用的sql_insert_string
,如下所示:
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 Server2008。因此,该数据库引发以下错误:
对象或列名称丢失或为空。 对于SELECT INTO语句,请验证每个列都有一个名称。 对于其他语句,请查找空别名。 不允许将别名定义为\\“ \\”或[]。 将别名更改为有效名称。
您可以像这样插入字节数组:
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);
}
我建议您像实体框架( http://www.asp.net/entity-framework )一样查看ORM( https://en.wikipedia.org/wiki/Object-relational_mapping )为您完成所有这些操作提高安全性和未来的变化要容易得多。
您在构造SQL查询时应该使用参数 ,这显然可以避免SQL注入攻击。 您的查询如何构造仍然不清楚。 这样的事情应该为您做。
SqlParameter sParam = new SqlParameter("@image_byte_array", SqlDbType.VarBinary)
{
Value = image
};
SqlHelper.ExecuteNonQuery(Transaction, CommandType.Text, sql_insert_string, sParam)
您可以使用
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语句构造为安全问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.