我在4行和4列的数据库中有一个表。每列包含不同的数据。
现在我想检索数据库中的所有数据,并将它们放在另一种形式的JLabel上。即
在我的数据库中。

packageName ...... monthlyFee ..... YearlyFee ....... TotalFee

常规....................... 150 .................. 300 ....... ............. 450

金....................................... 300 ......... 400 ...... 700

..... ..... .... ....

现在我有一个表格,我将4个空JLabel放在四行中,但是如何从数据库中检索值并将每个值放在适当的Label中呢?

这是我所做的,但仍然无法解决。我卡住了。

谢谢大家

 public void getPrices()
 {

  String srt ="SELECT * FROM program_tbl";

  try
    {
       con.connect();

       ps =  con.con.prepareStatement(srt);

       rs = ps.executeQuery();
       ResultSetMetaData data = rs.getMetaData();
       int colums = data.getColumnCount();

           while(rs.next())
           {

               Vector rows = new Vector();
               for (int i = 1; i < colums; i++)
               {
                   rows.addElement(rs.getObject(i));
               }


................................................... ..........

最佳答案

如果要以字符串形式获取此数据,则可以尝试执行以下操作:

Vector<String> rows = new Vector<String>();
while(rs.next())  {
   String rowEntry = rs.getString("packageName") +
                     rs.getString("monthlyFee") +
                     rs.getString("yearlyFee") +
                     rs.getString("totalFee") +
   rows.add(rowEntry);
}


如果不是String,而是以后使用的对象,则可以创建一个类:

public class MyObject {
    private String packageName;
    private int monthlyFee;
    private int yearlyFee;
    private int totalFee;

    public MyObject (String name, int monthlyFee, int yearlyFee, int totalFee) {
       this.packageName = name;
       this.monthlyFee = monthlyFee;
       this.yearlyFee = yearlyFee;
       this.totalFee = totalFee;
    }

    /*Setters
     *And
     *Getters*/
}


然后将其用作:

Vector<MyObject> rows = new Vector<MyObject>();
while (rs.next()) {
   MyObject obj = new MyObject(rs.getString("packageName")
                               , rs.getInt("montlyFee")
                               , rs.getInt("yearlyFee")
                               , rs.getInt("totalFee")
                               );
   rows.add(obj)
}


假设我们现在有一个带有字符串值的向量-Vector<String> rows;
现在我想创建那些JLabel。

JLabel[] myLabels = new JLabel[v.size()];
for(int i=0; i<rows.size(); i++) {
   as[i] = new JLabel(rows.get(i));
}


现在,我们已经准备好将一系列JLabel放入applet。

关于java - 从数据库获取值到JLabel,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19722829/

10-11 00:05
查看更多