简体   繁体   English

将jTable与MySQL数据库连接时,Java Net bean IDE 8.0中的数组越界异常

[英]Array Out Of Bounds exception in java net beans IDE 8.0 while connecting jTable with MySQL database

I have a table with 7 columns and I'm trying to connect my database with it so as to receive data from the database and show it in the table. 我有一个包含7列的表,并且试图将数据库与其连接,以便从数据库接收数据并将其显示在表中。 The code works fine when you press the button the first time but when you press it a second time, the table becomes blank and i get this error: 第一次按下按钮时,代码工作正常,但是第二次按下时,表变为空白,我得到此错误:

java.lang.ArrayIndexOutOfBoundsException: 0 >= 0

I have given my code below for the ActionPerformed method of the button. 我在下面给出了按钮的ActionPerformed方法的代码。

try
{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name","root","admin123");
    String query="SELECT * FROM tablename;";
    Statement st = con.createStatement();
    ResultSet rs= st.executeQuery(query);


    DefaultTableModel tmodel = (DefaultTableModel) jTable1.getModel();


    int rows=tmodel.getRowCount();
    while(rows>0)
    {
        tmodel.removeRow(0);
    }
    jTable1.setModel(tmodel);

while(rs.next())
{

    tmodel.addRow(new Object[] {rs.getInt("column1"),rs.getString("Column2"),rs.getString("Column3"),rs.getInt("Column4"),rs.getString("Column5"),rs.getString("Column6"),rs.getString("Column7")});
    jTable1.setModel(tmodel);
}

}
catch(Exception ex)
{
    System.out.println("Eception: "+ex);
}

Any help would be greatly appreciated. 任何帮助将不胜感激。

Since you never update rows inside the loop, the while will keep going forever or until an Exception is reached... 由于您从不更新循环内的rows ,因此while会一直持续下去,直到到达异常为止。

            while(rows>0)
            {
                tmodel.removeRow(0);
            }

And of course, setRowsCount() will be way simpler and less error prone. 当然, setRowsCount()会更简单,并且更不会出错。

BTW: Helping you would be easier if you pointed which line was the one throwing the exception. 顺便说一句:如果您指出哪一行是引发异常的行,对您的帮助会更加容易。

your problem is with this part although it is a relatively simple fix: 您的问题出在这部分,尽管它是一个相对简单的解决方法:

            int rows=tmodel.getRowCount();
            while(rows>0)
            {
                tmodel.removeRow(0);
            }
            jTable1.setModel(tmodel);

what you want to do is: 您想要做的是:

            while(tmodel.getRowCount()>0)
            {
                tmodel.removeRow(0);
            }
            jTable1.setModel(tmodel);

because you are setting a variable to a constant value returned by the method which means it wont be updated as you continue to delete rows 因为您正在将变量设置为方法返回的常量值,这意味着在继续删除行时不会对其进行更新

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

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