JTable中的ResultSet

时间:2010-03-23 09:37:50

标签: java swing jdbc jtable

如何在JTable中显示ResultSet。我正在使用此代码

 String [] record= new 
    String[ColCount]; 
    for (i=0; i<ColCount; i++) 
    { 
    record[i]=rset1.getString(i+1); 

    } 
    cell[i] = rset1.getString("loginname"); 
    cell[i] = rset1.getString( "role"); 
    System.out.println(cell[i][0]);
    //ItemGroup = rset1.getString( "Status"); 
    } 
    System.out.println(ItemCode);
    JTable jt = new JTable( 
    cell[i], headers);

但我只得到一行最后插入数据库。

2 个答案:

答案 0 :(得分:1)

您需要在代码周围放置一个while循环来迭代结果集。例如,

while(rset1.next())
{
//do something
}

答案 1 :(得分:0)

您列出的代码不完整/不可理解,但下面的代码显示了如何使用任意数量的列获取ResultSet并在JTable中显示其内容。

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;

private void viewTable(){
    //Perform database query here, which will open a Connection to the database
    //Assume we use the above query to populate a ResultSet results

    //Get information about the ResultSet
    ResultSetMetaData metaData = results.getMetaData();

    //Gets the number of columns in results
    int columnCount = metaData.getColumnCount();
    //Gets the name of each column in results
    String[] columnNames = new String[columnCount];
    for(int i = 0; i < columnNames.length; i++){
        columnNames[i] = metaData.getColumnLabel(i+1);
    }

    //You can use a String[] to keep track of the rows if you know the #
    //# of rows in the ResultSet, this implementation assumes that we don't
    //This ArrayList will keep track of each row in results (each row is
    //represented by a String[]
    ArrayList<String[]> rows = new ArrayList<>(); 
    while(results.next()){
        //Fetch each row from the ResultSet, and add to ArrayList of rows
        String[] currentRow = new String[columnCount];
        for(int i = 0; i < columnCount; i++){
            //Again, note that ResultSet column indecies start at 1
            currentRow[i] = results.getString(i+1);
        }
        rows.add(currentRow);
    }

    //Close Connection to the database here

    String[][] rowsArray = new String[rows.size()][columnCount];
    rowsArray = rows.toArray(rowsArray);
    table = new JTable(rowsArray, columnNames);
}