[英]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.