我目前正在通过按钮单击功能为表中的记录生成二维码图像,然后需要将生成的图像保存到表中。
但我只能生成二维码图像,似乎无法将图像存储到数据库中。给我的错误是:
不允许从数据类型nvarchar隐式转换为varbinary(max)。使用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();
发布于 2021-03-01 12:14:02
您需要实际发送字节,而不是将对象作为某种类型的字符串发送到数据库。
此外,最好使用显式数据类型定义参数,以避免C#对所需数据类型的猜测(不正确),就像这里对您所做的那样。
替换:
cmdupload.Parameters.AddWithValue("@qr", imgQRCode);
使用:
cmdupload.Parameters.Add("@qr", SqlDbType.VarBinary, -1 ).Value = byteImage;
显然,您还需要将数据库insert语句移动到您的
是为使其工作而定义的。
https://stackoverflow.com/questions/66416397
复制相似问题