Почему мои строки в Jtable не отображаются? - PullRequest
0 голосов
/ 21 октября 2018

Я не понимаю, почему, когда я выполняю свой запрос, верны только заголовки моего jtable, но строка не отображается.

Вот мой код

private void jButtonRequeteSqlExecuterActionPerformed(java.awt.event.ActionEvent evt) {                                                          
    try {

        //Taking the query from a txt
        String query = jTextPaneRequeteSql.getText();

        // Initialisation request time
        long start = System.currentTimeMillis();

        //Creating a statement
        Connection con = getConnection();
        Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet rs = st.executeQuery(query);            

        //Little manipulation to get the number of row
        rs.last();
        int rowCount = rs.getRow();

        //Calculate the time
        long totalTime = System.currentTimeMillis() - start;

        //Get the model
        jTableRequeteSql.setModel(buildTableModel(rs));

        //display the time
        jLabelRequeteSql.setText("La requête à été exécuter en " + totalTime + " ms et a retourné " + rowCount + " ligne(s)");
        System.out.println("La requête à été exécuter en " + totalTime + " ms et a retourné " + rowCount + " ligne(s)");

        //Refresh the display
        jTableRequeteSql.revalidate();
        jTableRequeteSql.repaint();

                //Closing connection
                rs.close();
                st.close();
                con.close();


          }
          catch (SQLException e) {
              //Dans le cas d'une exception, on affiche une pop-up et on efface le contenu
              JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR ! ", JOptionPane.ERROR_MESSAGE);
          }

}

Чтобы лучше понять мой код, вы должны знать: getConnection () - это функция, которая возвращает con (простое соединение с функцией базы данных).

Функция buildTableModel (rs) - это функция для создания динамической таблицы с номеромстолбцов и их имен динамически:

 public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {

ResultSetMetaData metaData = rs.getMetaData();

// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
    columnNames.add(metaData.getColumnName(column));
}

// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
    Vector<Object> vector = new Vector<Object>();
    for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
        vector.add(rs.getObject(columnIndex));
    }
    data.add(vector);
}

return new DefaultTableModel(data, columnNames);

}

1 Ответ

0 голосов
/ 21 октября 2018

Аааа, теперь я ясно вижу ...

rs.last();
int rowCount = rs.getRow();

Вы переместили курсор в конец ResultSet, но не сбросили его, поэтому, когда вы звоните ResultSet#next, происходит сбой, так как он уже в конце.

Вам необходимо использовать ResultSet#beforeFirst, чтобы сбросить курсор на начало ResultSet

И поскольку ваш код меня раздражает ...

//Taking the query from a txt
String query = jTextPaneRequeteSql.getText();

try (Connection con = getConnection();
        Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet rs = st.executeQuery(query)) {

    // Initialisation request time
    long start = System.currentTimeMillis();

    //Little manipulation to get the number of row
    rs.last();
    int rowCount = rs.getRow();

    //Calculate the time
    long totalTime = System.currentTimeMillis() - start;

    rs.beforeFirst();
    //Get the model
    jTableRequeteSql.setModel(buildTableModel(rs));

    //display the time
    jLabelRequeteSql.setText("La requête à été exécuter en " + totalTime + " ms et a retourné " + rowCount + " ligne(s)");
    System.out.println("La requête à été exécuter en " + totalTime + " ms et a retourné " + rowCount + " ligne(s)");

    //Refresh the display
    jTableRequeteSql.revalidate();
    jTableRequeteSql.repaint();

} catch (SQLException e) {
    //Dans le cas d'une exception, on affiche une pop-up et on efface le contenu
    JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR ! ", JOptionPane.ERROR_MESSAGE);
}

См. try-with-resources для получения более подробной информации

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...