JTable从MySQL数据库获取值

时间:2014-07-25 14:10:26

标签: java mysql swing jdbc jtable

我需要从数据库中获取所有值并将其放在JTable中,填充所有行。 我的代码只是放在最后一行的JTable中,并且错过了之前的所有内容。 任何人都知道如何从数据库中获取所有值并将它们全部插入JTable中?

try{
            Class.forName("com.mysql.jdbc.Driver");
            conn3 = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=123456");
            stmt3 = conn3.createStatement();
            rs3 = stmt3.executeQuery("SELECT * FROM teams");
            String str1 = null,str2 = null,str3 = null,str4 = null,str5 = null;
            while (rs3.next())
            {
                str1 = rs3.getString(1);
                str2 = rs3.getString(2);
                str3 = rs3.getString(3);
                str4 = rs3.getString(4);
                str5 = rs3.getString(5);
            }

            Object[][] data = {{str1,str2,str3,str4,str5}};
            String[] columnNames = {"id","Name","Players","Point","Position" };
            table = new JTable(data,columnNames);
            table.setCellSelectionEnabled(true);
            table.setColumnSelectionAllowed(true);
            table.setFillsViewportHeight(true);
            table.setSurrendersFocusOnKeystroke(true);
            table.setBounds(10, 321, 297, 143);
            frame.getContentPane().add(table);
            rs3.close();
            stmt3.close();
            conn3.close();
    }
    catch (SQLException se)
    {
        System.out.println( "SQL Exception:" );
           while( se != null )
           {
              System.out.println( "State  : " + se.getSQLState()  );
              System.out.println( "Message: " + se.getMessage()   );
              System.out.println( "Error  : " + se.getErrorCode() );
              se = se.getNextException();
           }
    }
    catch (ClassNotFoundException ex)
    {
           System.out.println("Error: unable to load driver class!");
    }

3 个答案:

答案 0 :(得分:2)

while (rs3.next())
        {
            str1 = rs3.getString(1);
            str2 = rs3.getString(2);
            str3 = rs3.getString(3);
            str4 = rs3.getString(4);
            str5 = rs3.getString(5);
        }

你一遍又一遍地覆盖相同的变量。您应该使用列表或数组。类似的东西:

while (rs3.next())
        {
            //Given that all of your str are declared as List<String> strX = new List<String>();
            str1.add(rs3.getString(1));
            str2.add(rs3.getString(2));
            str3.add(rs3.getString(3));
            str4.add(rs3.getString(4)); 
            str5.add(rs3.getString(5));
        }

但是为了在表格中插入ResultSet,有plenty of tutorials


编辑:如果您不想使用表格模型,则可以更改数据检索的逻辑。您必须向表格提供矩阵[row] [col]。你的行是哪一行?你的colums哪个?

行是结果集的“nexts”,而colums是1到5.你需要知道有多少行(有点棘手):

if (rs3.next()) {
        rs3.last();
        int rows = rs3.getRow();
    }
rs3.beforeFirst();

现在创建矩阵:

String[][] matrix = new String[rows][4]; //Your Object[][] data.

int index = 0;
while(rs3.next()){
    matrix[i][0] = rs3.getString(1);
    matrix[i][1] = rs3.getString(2);
    matrix[i][2] = rs3.getString(3);
    matrix[i][3] = rs3.getString(4); 
    matrix[i][4] = rs3.getString(5);
    i++;
}
String[] columnNames = {"id","Name","Players","Point","Position" };
table = new JTable(matrix, columnNames);

USEFUL:检索对象数据的另一个有用(但不是严格要求的)方法是using customized mappings或更复杂的对象关系映射框架,如Hibernate

答案 1 :(得分:1)

不要使用2D数组来保存数据。您不知道数据库中将包含多少行数据,因此您不知道制作数据的大小。

查看Table From Database以获取一些不同的建议。一种方法涉及使用Vectors,因此您可以使用DefaultTableModel。

答案 2 :(得分:0)

OP代码使用2d对象数组作为JTable的数据,但从不将数据移动到该数组中。我们首先需要计算表中有多少行,以便我们可以调整数组的大小:

try {
        Class.forName("com.mysql.jdbc.Driver");
        conn3 = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=123456");
        stmt3 = conn3.createStatement();
        ResultSet rowCounter = stmt3.executeQuery("SELECT COUNT(*) FROM teams");
        rowCounter.next();
        int numRows = rowCounter.getInt(1);
        stmt3.close();            
        Object[][] data = new Object[numRows][5];
        stmt3 = conn3.createStatement();
        rs3 = stmt3.executeQuery("SELECT * FROM teams");
        int row = 0;
        while (rs3.next()) {
            data[row][0] = rs3.getString(1);
            data[row][1] = rs3.getString(2);
            data[row][2] = rs3.getString(3);
            data[row][3] = rs3.getString(4);
            data[row][4] = rs3.getString(5);
            row++;
        }
        String[] columnNames = {"id","Name","Players","Point","Position" };
        table = new JTable(data,columnNames);
        table.setCellSelectionEnabled(true);
        table.setColumnSelectionAllowed(true);
        table.setFillsViewportHeight(true);
        table.setSurrendersFocusOnKeystroke(true);
        table.setBounds(10, 321, 297, 143);
        frame.getContentPane().add(table);
        rs3.close();
        stmt3.close();
        conn3.close();
}
catch (SQLException se) {
    //handle this
}
catch (ClassNotFoundException ex) {
       System.out.println("Error: unable to load driver class!");
}