本文介绍了将Byte []数组保存到MYSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能在这里回答:将图像存储为byte []到Mysql使用asp.net和c#

using System.Drawing;
using System.Drawing.Imaging;

var imageBytes = imageToByteArray(pictureBox1.Image);

var insert = new MySqlCommand("Insert INTO itemimage set imageName = '" + imageBytes + "'", _con);

insert.ExecuteNonQuery();


public byte[] imageToByteArray(Image imageIn)
{
    var ms = new MemoryStream();
    imageIn.Save(ms, ImageFormat.Gif);
    return ms.ToArray();
}


Table: itemimage
2 | System.Byte[]  | 13byte

3 | System.Byte[]  | 13byte

此代码有什么问题?谢谢.

What is wrong with this code? thanks.

推荐答案

您正在使用字符串串联来形成SQL.那就是在字节数组上调用 ToString ,这将给出 System.Byte [] 作为结果.

You're using string concatenation to form the SQL. That's calling ToString on a byte array, which gives System.Byte[] as the result.

相反,请使用参数化查询,并将参数值设置为您的字节数组.

Instead, use a parameterized query, and set the parameter value to your byte array.

类似这样的东西:

var data = ImageToByteArray(pictureBox.Image);
using (var cmd = new MySqlCommand("INSERT INTO itemimage SET imageName = @image",
                                  _con))
{
    cmd.Parameters.Add("@image", MySqlDbType.Blob).Value = data;
    cmd.ExecuteNonQuery();
}

请介意,我在这里有点担心列名-真的是要作为图像的 name (这就是列名所暗示的)还是图片中的数据(这是您的代码所建议的)?这两件事是完全不同的,您应该清楚说明哪个是哪个.

Mind you, I'm a bit concerned about the column name here - is it really meant to be the name of an image (which is what the column name suggests) or the data in an image (which is what your code suggests)? Those are two very different things, and you should make it clear which is which.

您应该始终使用参数化查询:

You should always use parameterized queries:

  • 它们可以防止 SQL注入攻击
  • 它们减少了数据转换问题
  • 他们更清晰地将代码与数据分离

这篇关于将Byte []数组保存到MYSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 12:49