Retrieve LONGBLOB from MySQL in C#

空扰寡人 提交于 2019-12-03 18:11:25

问题


I want to retrieve a LONGBLOB from my MySQL database but I don't know how. I have searched the interwebz and nothing really helpful (understandable) was found. When I retrieve the LONGBLOB, I want to save it as a image.

This is what I already tried:

        int bufferSize = 100;
        byte[] bin = new byte[bufferSize];
        long retval = 0;
        long startIndex = 0;

        MemoryStream ms = null;
        Image image = null;

        MySqlCommand command = new MySqlCommand("select * from image where uid = @uid", Connection.Connect());
        command.Parameters.AddWithValue("@uid", "2");
        MySqlDataReader reader = command.ExecuteReader();

        if (reader.Read())
        {
            retval = reader.GetBytes(reader.GetOrdinal("logo"), startIndex, bin, 0, bufferSize);
        }


        ms = new MemoryStream(bin);
        image = Image.FromStream(ms);

Thanks in advance.


回答1:


I actually did this as part of a project I was working on...

public Bitmap loadImage(int imgID)
        {

            MySqlDataReader myData;
            MySqlCommand cmd = new MySqlCommand();

            string SQL;
            byte[] rawData;
            MemoryStream ms;
            UInt32 FileSize;
            Bitmap outImage;

            SQL = "SELECT ImageName, ImageSize, Image FROM Images WHERE ImageID =";
            SQL += imgID.ToString();

            try
            {
                cmd.Connection = connection;
                cmd.CommandText = SQL;

                myData = cmd.ExecuteReader();

                if (!myData.HasRows)
                    throw new Exception("There are no blobs to save");

                myData.Read();

                FileSize = myData.GetUInt32(myData.GetOrdinal("ImageSize"));
                rawData = new byte[FileSize];

                myData.GetBytes(myData.GetOrdinal("Image"), 0, rawData, 0, (Int32)FileSize);


                ms = new MemoryStream(rawData);
                outImage = new Bitmap(ms);
                ms.Close();
                ms.Dispose();

                myData.Close();
                myData.Dispose();

                cmd.Dispose();

                return outImage;


            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }

        }

Hope this helps. Also please excuse any bad coding practices, this was written a while ago.

Thanks Tom




回答2:


i'm not sure, but i think you can try this: http://www.techrepublic.com/article/utilize-adonet-and-c-to-work-with-blob-data/5766889

stefan



来源:https://stackoverflow.com/questions/8257941/retrieve-longblob-from-mysql-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!