从数据库中检索多个图像

时间:2014-11-14 05:32:21

标签: c# mysql

所以我正在做我的第一个项目,而现在那里的东西让我有点疯狂而且我一直在寻找,但我似乎无法找到答案。

我的数据库中有两个表,一个用于员工数据(employeedata),另一个用于他们家中的图片(housepictures),只有三个字段(PhotoID,EmployeeID,Photo),使用外键到来自employeesedata表的EmployeeID。

我试图从这张桌子中检索图片并将它们放在各自的PictureBox中(总共有六张,因为我只为员工存储了6张图片),但我还是只设法检索第一张图片,或最后一张图片,或者在每张PictureBox中重复它(同一张照片)。这是我目前的代码:

    try
    {
        using (MySqlConnection conn = new MySqlConnection(connDB.connstring))
        {
            using (MySqlCommand cmd = new MySqlCommand("select HousePicture from Employees.housepictures where EmployeeID='" + id + "'", conn))
            {
                conn.Open();

                using (MySqlDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.Read())
                    {

                        PictureBox[] pb = { pictureBoxHouse1, pictureBoxHouse2, pictureBoxHouse3, pictureBoxHouse4, pictureBoxHouse5, pictureBoxHouse6 };

                        for (int i = 0; i < pb.Length; i++)
                        {
                            using (MemoryStream stream = new MemoryStream())
                            {

                                if (dr["HousePicture"] != DBNull.Value)
                                {
                                    byte[] image = (byte[])dr["HousePicture"];
                                    stream.Write(image, 0, image.Length);
                                    Bitmap bitmap = new Bitmap(stream);
                                    pb[i].Image = bitmap;
                                }
                            }
                        }

                    }
                }
            }
        }
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

非常感谢任何建议!

1 个答案:

答案 0 :(得分:1)

首先尝试获取结果,然后使用while(而不是if)循环浏览所有返回的记录。您可以按原样保留大部分代码,并在循环的每次迭代中递增计数器,以便在数组中设置正确的PictureBox

PictureBox[] pb = { pictureBoxHouse1, pictureBoxHouse2, pictureBoxHouse3,
                    pictureBoxHouse4, pictureBoxHouse5, pictureBoxHouse6 };

using (MySqlDataReader dr = cmd.ExecuteReader())
{
    int i = 0;

    while (dr.Read())
    {
        using (MemoryStream stream = new MemoryStream())
        {
            if (dr["HousePicture"] != DBNull.Value)
            {
                byte[] image = (byte[])dr["HousePicture"];
                stream.Write(image, 0, image.Length);
                Bitmap bitmap = new Bitmap(stream);
                pb[i].Image = bitmap;
            }
        }

        i++;
    }
}