如何使用C#在查询中传递字节数组?

时间:2014-02-15 11:26:16

标签: c# sql

我正在尝试在数据库中插入字节数组的字节。使用以下代码。

String query = String.Format(@"INSERT INTO [Documents]
                              ([InsertedBy], [DocumentName], [Document])
                              VALUES
                              ('{0}','{1}',{2})",
                              insertedBy, docName, docBytes);

Cmd.CommandText = query;
Cmd.ExecuteNonQuery();

发生以下异常:

  

对象或列名称缺失或为空。对于SELECT INTO   声明,验证每列是否有名称。对于其他陈述,请查看   对于空别名。不允许使用定义为“”或[]的别名。   将别名更改为有效名称。 ''。

附近的语法不正确

我不知道原因是什么。

2 个答案:

答案 0 :(得分:1)

永远不要使用字符串连接或字符串函数来进行参数化查询。

另外,因为(我怀疑)docBytesbyte[],字符串连接将不会有您希望的结果。

我将如何做到这一点:

private static void InsertDocument(SqlCommand cmd, int insertedBy, string docName, byte[] docBytes)
{
    cmd.CommandText = @"INSERT INTO [Documents]
                        ([InsertedBy], [DocumentName], [Document])
                        VALUES
                        (@insertedBy,@docName,@docBytes)";
    cmd.Parameters.Add("insertedBy", SqlDbType.Int).Value = insertedBy;
    // Note: consider using `nvarchar` instead of `varchar`;
    cmd.Parameters.Add("docName", SqlDbType.VarChar, 100).Value = docName;
    // Note: -1 maps to the nvarchar(max) length;
    cmd.Parameters.Add("docBytes", SqlDbType.VarBinary, -1).Value = docBytes;

    // The following call presupposes that the associated `SqlConnection` is open
    cmd.ExecuteNonQuery();
}

答案 1 :(得分:0)

如果您的insertedBy列是int,则无需使用单引号。因为您尝试在int类型列中插入字符。

就像使用它一样;

string query = String.Format(@"INSERT INTO [Documents]
                              ([InsertedBy], [DocumentName], [Document])
                              VALUES
                              ({0},'{1}',{2})",
                              insertedBy, docName, docBytes);

但由于我们不知道你的价值观,这是我唯一的建议。

相关问题