C# 将字节数组插入SQL Server

C# 将字节数组插入SQL Server,c#,sql-server,C#,Sql Server,我正在构造一个sql\u insert\u字符串,用于Microsoft.ApplicationBlocks.Data.SqlHelper,如下所示: SqlHelper.ExecuteNonQuery(Transaction, CommandType.Text, sql_insert_string) 当我将鼠标悬停在SQL语句上时,它如下所示: string sql_insert_string = "Insert into images_table(image_id, image_

我正在构造一个
sql\u insert\u字符串
,用于
Microsoft.ApplicationBlocks.Data.SqlHelper
,如下所示:

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[])
插入值之一是如上所示的字节数组。变量在字节数组中有值,比如说像字节[6738]。但是在构造了
sql\u insert\u字符串之后,它就变成了
System.Byte[]
image\u byte\u数组
列类型为
varbinary(max)
。数据库是SQL Server 2008。因此,数据库引发以下错误:

对象或列名丢失或为空。对于SELECT INTO语句,请验证每个列都有名称。对于其他语句,请查找空别名。不允许使用定义为\“\”或[]的别名。将别名更改为有效名称

你可以用

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语句。

您可以像这样插入字节数组:

        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);
        }

我建议您使用类似Entity Framework()的ORM()来完成所有这一切,同时提高安全性,并使将来的更改更加容易。

在构建SQL查询时,您应该使用参数,这显然将避免SQL注入攻击。这里还不清楚您的查询是如何构造的。 像这样的东西应该适合你

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

sql字符串生成器只需对类型为
byte[]
的变量调用
ToString()
。显示创建sql查询字符串的方法您不应该构造sql语句-您应该使用参数来避免sql注入攻击
SqlParameter
不仅可以避免SQL注入,而且不会出现这样的问题,因为所有输入值都将正确地“转换”为SqlParameter。您创建的SQL语句不正确。