Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

sql

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.

like image 490
AndroidLearner Avatar asked Feb 15 '14 11:02

AndroidLearner


1 Answers

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();
}
like image 76
Jean Hominal Avatar answered Oct 19 '22 23:10

Jean Hominal