[英]Conversion from nvarchar to varbinary(max)
I am currently generating a QR code image for records in a table through a button click function, and then the image generated would need to be saved into the table.我目前正在通过按钮单击 function 为表格中的记录生成二维码图像,然后需要将生成的图像保存到表格中。
But I am only able to generate the QR code image only and I can't seem to store the image into the database.但我只能生成二维码图像,我似乎无法将图像存储到数据库中。 The error given to me is:给我的错误是:
Implicit conversion from data type nvarchar to varbinary(max) is not allowed.不允许从数据类型 nvarchar 到 varbinary(max) 的隐式转换。 Use the CONVERT function to run this query.使用 CONVERT function 运行此查询。
I have search various methods online yet I can't seem to understand how the CONVERT function actually works.我在网上搜索了各种方法,但我似乎无法理解 CONVERT function 的实际工作原理。 Below is my code:下面是我的代码:
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();
Instead of posting an object to the database, which is being sent as a string of some kind, you need to actually send the bytes.您需要实际发送字节,而不是将 object 作为某种字符串发送到数据库中。
Also it's a good idea to define the parameter with an explicit data type to avoid C# guessing (incorrectly) at your required data type as it has done to you here.此外,使用显式数据类型定义参数也是一个好主意,以避免 C# (错误地)猜测您所需的数据类型,就像它在此处对您所做的那样。
Replace:代替:
cmdupload.Parameters.AddWithValue("@qr", imgQRCode);
With:和:
cmdupload.Parameters.Add("@qr", SqlDbType.VarBinary, -1 ).Value = byteImage;
Obviously you will also need to move the database insert statement to a scope where your byteImage
is defined for this to work.显然,您还需要将数据库插入语句移动到 scope ,您的byteImage
已在其中定义以使其工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.