【问题标题】:Conversion from nvarchar to varbinary(max)从 nvarchar 转换为 varbinary(max)
【发布时间】:2021-05-30 15:20:33
【问题描述】:

我目前正在通过按钮单击功能为表格中的记录生成二维码图像,然后需要将生成的图像保存到表格中。

但我只能生成二维码图像,我似乎无法将图像存储到数据库中。给我的错误是:

不允许从数据类型 nvarchar 到 varbinary(max) 的隐式转换。使用 CONVERT 函数运行此查询。

我在网上搜索了各种方法,但我似乎无法理解 CONVERT 函数的实际工作原理。以下是我的代码:

string toinsertcode = "Consignment Number: " + txtConsignmentNum.Text +
   "\n" + "Student ID: " + txtStudentID.Text;

QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(toinsertcode, QRCodeGenerator.ECCLevel.Q);

System.Web.UI.WebControls.Image imgQRCode = new System.Web.UI.WebControls.Image();
imgQRCode.Height = 150;
imgQRCode.Width = 150;
using (Bitmap bitmap = qrCode.GetGraphic(80))
{
    using (MemoryStream ms = new MemoryStream())
    {
        bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        byte[] byteImage = ms.ToArray();
        imgQRCode.ImageUrl = "data:image/png;base64, " + Convert.ToBase64String(byteImage);
    }
    placeholderQR.Controls.Add(imgQRCode);
}      

conn.Open();
string insertqrcode = "INSERT INTO Parcel(QRCode) values(@qr)"; 
SqlCommand cmdupload = new SqlCommand(insertqrcode, conn);
cmdupload.Parameters.AddWithValue("@qr", imgQRCode); 
cmdupload.ExecuteNonQuery();
conn.Close();  

【问题讨论】:

  • 第一件事,永远不要使用AddWithValue自己构建正确的参数。这实际上可能是问题所在,它可能在您的字节数组上调用 ToString(),这是错误的。
  • 您正在将图像类型的对象保存到 DB。我认为您应该保存 byteImage 字节数组。

标签: c# sql asp.net sql-server


【解决方案1】:

您需要实际发送字节,而不是将对象作为某种字符串发送到数据库。

此外,使用显式数据类型定义参数也是一个好主意,以避免 C# 猜测(错误地)您所需的数据类型,就像这里对您所做的那样。

替换:

    cmdupload.Parameters.AddWithValue("@qr", imgQRCode); 

与:

    cmdupload.Parameters.Add("@qr", SqlDbType.VarBinary, -1 ).Value = byteImage;

显然,您还需要将数据库插入语句移动到您的 byteImage 定义的范围内以使其工作。

【讨论】:

  • 您需要将{ Value = byteImage } 添加到您的第二行。
  • 我用这里建议的命令替换了原始命令,它就像一个魅力!谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2020-12-26
相关资源
最近更新 更多