简体   繁体   English

如何将每个数据库表行传递到 Java mysql 中的相关 jLabels

[英]How to pass Each database table row into relavent jLabels in Java mysql

i am create a simple rating system.我正在创建一个简单的评级系统。 i have only 3 question the database table.我只有 3 个问题数据库表。 i attached screen shot image below.我在下面附上了屏幕截图。

在此处输入图像描述

those question are ab c what i need is i have put 3 jLabels in JFrame i need to fetch the from database table and pass in to relavent Jlables i attached the screen shot below.这些问题是 ab c 我需要的是我在 JFrame 中放置了 3 个 jLabels 我需要从数据库表中获取并传递给相关的 Jlables 我附上了下面的屏幕截图。

在此处输入图像描述

but result only displayed c only means last row data only displayed.但结果仅显示 c 仅表示仅显示最后一行数据。 i need to display question 1 - a, question 2 - b,question 3 - c.我需要显示问题 1 - a,问题 2 - b,问题 3 - c。 how to do it what i tried so far i attached below.到目前为止,我在下面附上了我尝试过的方法。

public void question()
    {
    
      String query = "select * from rate";
      Statement stat =null;
      ResultSet rs;
     
          try {
            stat = con.createStatement();
             rs = stat.executeQuery(query);
              
              while(rs.next())
              {
                  lblq1.setText(rs.getString(2));
                  lblq2.setText(rs.getString(2));
                  lblq3.setText(rs.getString(2));
              }
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
         
    }

Try changing this:尝试改变这个:

          while(rs.next())
          {
              lblq1.setText(rs.getString(2));
              lblq2.setText(rs.getString(2));
              lblq3.setText(rs.getString(2));
          }

into something like this:变成这样的东西:

          int id = 1; 
          while(rs.next())
          {
              if ( id == 1 ) lblq1.setText(rs.getString(2));
              if ( id == 2 ) lblq2.setText(rs.getString(2));
              if ( id == 3 ) lblq3.setText(rs.getString(2));
              id += 1;
          }

In your current code, you set the text for all three feelds for every value, and you end up with all of them containing the last value.在您当前的代码中,您为每个值设置了所有三种感觉的文本,最终所有这些感觉都包含最后一个值。 You need to check which value you want to set in which field.您需要检查要在哪个字段中设置哪个值。 There are better (more efficient) ways to write this code (switch / if else if ) but for an example, this should be sufficient.有更好(更有效)的方法来编写此代码(switch / if else if),但例如,这应该足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM