简体   繁体   中英

how to upload bytes[] to varbinary(max) from blob to sql

I'm attempting to populate this field:

在此处输入图像描述

Here's how I do it:

using (SqlConnection conn = new SqlConnection(connectionString))
{
    conn.Open();
    SqlTransaction transaction = conn.BeginTransaction();

    //here we are iterating through a list of queries that we want to execute inside of this transaction
    foreach (var query in queries)
    {
        //retrieve blob bytes from azure
        byte[] tifBytes = ReadInputName(query.TifFileName);
        byte[] rtfBytes = ReadInputName(query.RtfFileName);

        SqlCommand cmd = new SqlCommand(query.Query, conn, transaction);
        var rtfBytesParam = new SqlParameter("@rtfBytes", SqlDbType.Binary)
        {
            Value = rtfBytes
        };
        var tifBytesParam = new SqlParameter("@tifBytes", SqlDbType.Binary)
        {
            Value = tifBytes
        };
        cmd.Parameters.Add(rtfBytesParam);
        cmd.Parameters.Add(tifBytesParam);
        int rowsAffected = cmd.ExecuteNonQuery();
    }

    transaction.Commit();
}

Here are the exceptions I am getting, specifically Core.Net SqlClient Data Provider: Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.

在此处输入图像描述

Please note that the queries being executed look like this:

在此处输入图像描述

What am I doing wrong? How do we insert a blob into a varbinary(max) field?

You're inserting the literal parameter names ( '@tifBytes' ), which causes SQL to try and insert the string "@tifBytes" in a VARBINARY column, hence the error. Remove the single quotes around your parameters.

Also, don't build SQL like this. Filenames can have single quotes in them. Sure, it looks like one piece of code builds the SQL and another piece supplies the parameters and runs the query, but then redesign that.

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