Question

I'm trying to insert values to my table which contains varbinary(MAX), and the file I try to insert is byte[]

 public DataTable add1(string docName , byte[] doc)
{
    DBAdaptor db = new DBAdaptor();
    string query = "INSERT INTO [Document]    (DocumentName, DocumentData) OUTPUT       inserted.DocumentID VALUES        (N'" + docName + "' , " + doc + ")";
    return db.QueryRide(query);
}

and I get this exception :

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 ''.

and here is the function which execute my query:

public DataTable QueryRide(string query)
{
    DataTable dt = new DataTable();
    string conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;        
    SqlConnection con = new SqlConnection(conStr);
    SqlCommand cmd = new SqlCommand(query, con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    try
    {
        con.Open();
        da.Fill(dt);
    }
    catch (Exception)
    {
       throw;
    }
    finally
    {
        if (con.State == ConnectionState.Open)
            con.Close();
    }
    return dt;
}

how can I insert this byte[] to my table? thanks

Was it helpful?

Solution

Try this:

private static int insertDocument(string name, byte[] data)
{
    using (SqlConnection cn = new SqlConnection("..."))
    using (SqlCommand cm = cn.CreateCommand())
    {
        cm.CommandText = @"
            INSERT INTO [Document] (DocumentName, DocumentData)
            OUTPUT      inserted.DocumentID
            VALUES      (@Name, @Data)";
        cm.Parameters.AddWithValue("@Name", name);
        cm.Parameters.AddWithValue("@Data", data);
        cn.Open();
        return (int)cm.ExecuteScalar();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top