简体   繁体   中英

How to pass Byte Array in a Query using C#?

I'm trying to insert bytes of byte array in the database. using following code.

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

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

Following exception is occured:

An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name. Incorrect syntax near ''.

I'm not getting what the reason is.

Never use string concatenation or string functions to make parametrized queries.

Also, because (I suspect that) docBytes is a byte[] , string concatenation will not have the results that you hope for.

Here is how I would do it:

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

If your insertedBy column is an int , you don't need to use single quotes with it. Because you are try to insert characters to your int typed column.

Just use it like;

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

But since we don't know your values, this is the only suggestion I have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM