【问题标题】:C# - How to use MySQL with reader GetValue function and with for loopC# - 如何将 MySQL 与读取器 GetValue 函数和 for 循环一起使用
【发布时间】:2017-12-20 14:01:11
【问题描述】:

在我的 MySQL 数据库中存储了图像。我现在可以显示这些图片。但不幸的是,我的代码只适用于一张图片。我想显示表格中的所有图片,但使用rdr.Nextresult() 不起作用。

我有一个 PicutreBox 数组:

PictureBox[] pictureboxes = new PictureBox[30];

我为每个索引生成新的图片框:

for (int i = 0; i < pictureboxes.Length; i++)
{
    pictureboxes[i] = new PictureBox();
}

这是我到目前为止所做的:

MySqlConnection conn = new MySqlConnection(connStr);
try
{
    conn.Open();
    string sql = "SELECT image FROM drinks";
    MySqlCommand cmd = new MySqlCommand(sql, conn);
    MySqlDataReader rdr = cmd.ExecuteReader();

    if (rdr.Read())
    {
        for (int i = 0; i < anzahl; i++)
        {
            pictureboxes[i].Location = new System.Drawing.Point(80 + i * 100, 40);
            pictureboxes[i].Name = "pictureBox" + i;
            pictureboxes[i].SizeMode = PictureBoxSizeMode.Zoom;
            pictureboxes[i].Size = new System.Drawing.Size(300, 300);
            pictureboxes[i].Image = ByteArrayToImage((byte[])(rdr.GetValue(0)));
            panel1.Controls.Add(pictureboxes[i]);
            //rdr.NextResult();
        }
    }
    rdr.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}
conn.Close();

ByteArrayToImage 函数:

public static Image ByteArrayToImage(byte[] byteArrayIn)
{
    using (MemoryStream ms = new MemoryStream(byteArrayIn))
    {
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }
}

当我将rdr.GetValue(0) 更改为rdr.GetValue(i) 时,索引超出范围。 我必须如何更改代码才能输出表格中的所有图像?

【问题讨论】:

  • 在谷歌上搜索如何在调用command.ExecuteReader() 方法时使用while 循环,你不使用if (rdr.Read()),网上有很多工作示例。
  • 将 if (rdr.Read()) 更改为 while (rdr.Read())
  • pictureboxes[i].Image = ByteArrayToImage((byte[])(rdr.GetValue(0))) 这应该使用列名而不是序号位置pictureboxes[i].Image = ByteArrayToImage((byte[])(rdr.["YourColumn"]) 访问,并在必要时进行适当的转换。

标签: c# mysql


【解决方案1】:

您的rdr.GetValue(0) 用户正在访问您从查询SELECT image FROM drinks 返回的单列。如果您尝试将其更改为使用您的索引变量i(用于访问您的行),您将遇到您所看到的问题。

您可以将GetValue 方法的用法更改为:rdr.GetValue("image"),它的工作方式与rdr.GetValue(0) 相同。

   for (int i = 0; i < anzahl; i++)
   {
      pictureboxes[i].Location = new System.Drawing.Point(80 + i * 100, 40);
      pictureboxes[i].Name = "pictureBox" + i;
      pictureboxes[i].SizeMode = PictureBoxSizeMode.Zoom;
      pictureboxes[i].Size = new System.Drawing.Size(300, 300);
                pictureboxes[i].Image = ByteArrayToImage((byte[])(rdr.GetValue("image")));
      panel1.Controls.Add(pictureboxes[i]);
      //rdr.NextResult();
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多