循环仅返回第一行

时间:2015-01-23 10:05:10

标签: java

我试图将数据库的结果加载到jtable中,但是当我运行代码时,它只显示第一行,然后错误地发现没有找到数据的异常。这是我的代码;

try {

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\Users\\PMatope.FMBMW.000\\Documents\\Library.accdb";
            conn = DriverManager.getConnection(url, "", "");

            st = conn.createStatement();

            ResultSet rs = st.executeQuery("SELECT ID,full_name,sex,course,contact,email FROM Person");
            ResultSetMetaData data = rs.getMetaData();


            DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
           // jTable1.setModel(model);

             while (rs.next()) {

                  String id,fname,sex,course,contact,email;
                  id = rs.getString("ID");
                  fname = rs.getString("full_name");
                  sex = rs.getString("sex");
                  course = rs.getString("course");
                  contact = rs.getString("contact");
                  email = rs.getString("email");

                   model.addRow(new Object[] {id,fname,sex,course,contact,email});
                   model.fireTableDataChanged();
                   JOptionPane.showMessageDialog(null, rs.getString("sex"));
              }



        } catch (Exception e) {
             JOptionPane.showMessageDialog(null,"Message: "+ e.getMessage());
        }

2 个答案:

答案 0 :(得分:0)

你需要初始化,

DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
在你的while循环中

答案 1 :(得分:0)

首先声明您的表模型并为每个循环时间创建新实例。

例如。 :

DefaultTableModel model = null;
           // jTable1.setModel(model);

             while (rs.next()) {

                  model = (DefaultTableModel) jTable1.getModel();

                  String id,fname,sex,course,contact,email;
                  id = rs.getString("ID");
                  fname = rs.getString("full_name");
                  sex = rs.getString("sex");
                  course = rs.getString("course");
                  contact = rs.getString("contact");
                  email = rs.getString("email");

                   model.addRow(new Object[] {id,fname,sex,course,contact,email});
                   model.fireTableDataChanged();
                   JOptionPane.showMessageDialog(null, rs.getString("sex"));
              }