如何使用C#在查询中传递字节数组?
我试图在数据库中插入字节数组的字节。使用下面的代码如何使用C#在查询中传递字节数组?,c#,sql,C#,Sql,我试图在数据库中插入字节数组的字节。使用下面的代码 String query = String.Format(@"INSERT INTO [Documents] ([InsertedBy], [DocumentName], [Document]) VALUES ('{0}','{1}',{2})",
String query = String.Format(@"INSERT INTO [Documents]
([InsertedBy], [DocumentName], [Document])
VALUES
('{0}','{1}',{2})",
insertedBy, docName, docBytes);
Cmd.CommandText = query;
Cmd.ExecuteNonQuery();
发生以下异常:
对象或列名丢失或为空。选择进入
语句,验证每列是否有名称。对于其他语句,请参见
用于空别名。不允许使用定义为“”或[]的别名。
将别名更改为有效名称。“”附近的语法不正确
我不明白原因是什么。如果您的
insertedBy
列是int
,则不需要对其使用单引号。因为您正在尝试将字符插入到int
typed列中
就这样使用它
string query = String.Format(@"INSERT INTO [Documents]
([InsertedBy], [DocumentName], [Document])
VALUES
({0},'{1}',{2})",
insertedBy, docName, docBytes);
但由于我们不知道您的值,这是我唯一的建议。切勿使用字符串串联或字符串函数进行参数化查询 另外,由于(我怀疑)
docBytes
是一个byte[]
,字符串串联将不会得到您希望的结果
我会这样做:
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();
}
这些列的类型是什么?你的
insertedBy
、docName
和docBytes
的值到底是什么?insertedBy是int,documentname是varchar(100),Document是VarBinary(max),我总是以这种方式插入VarBinary作为参数:,因为根据它的名称,它似乎是一个原始的byte[]
类型。你不应该以这种方式编码SQL,这是容易受影响的,我赞成。不要自己伪造SQL查询。使用ADO.NET或类似的库来翻译基础数据库方言。我不是专家,但我认为docBytes
也可能是个问题,例如,如果它是byte[]
。问题中的错误消息可能表示类似的情况。即使删除了引号,也会出现相同的错误,这可以确保这些引号不是问题的原因