0

I am doing java project in NetBeans 8 using databases and GUI.The problem is appearing when I search through the database and add the found values to JTable: all values are being added only to first column of JTable while I need them added separately to corresponding columns. I tried getColumnCount() and it also gave me 1 meaning that I have only one column. How to add database values to JTable's corresponding columns?

I've tried all the populating functions adviced here

My code:

jTable1 = new javax.swing.JTable();

       String sql = "SELECT (flight_id, plane_name, dep_city, arival_city, date_month, date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats) FROM flight "
                 + "WHERE (dep_city = '" + SearchFlight.getFromCity() + "' AND " 
                 + "arival_city = '" + SearchFlight.getToCity() + "' AND "
                 + "date_month = '" + SearchFlight.getMonth() + "');";

        PreparedStatement stat = conn.prepareStatement(sql);
        ResultSet rs = stat.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs)
    );
jScrollPane1.setViewportView(jTable1);

SearchFlight is a GUI class, and its methods return strings obtained in GUI. DbUtils.resultSetToTableModel(rs)is a method in net.proteanit.sql.DbUtils;

So, it is expected that the data will be filled into 9 columns, hoewever it fills all the data into one column.

Community
  • 1
  • 1

1 Answers1

2
SELECT ( ... )

must be

SELECT .... 

And better use the PreparedStatement as intended. Otherwise SQL injection still is possible. And try-with-resources closes the things under all circumstances.

    String sql = "SELECT flight_id, plane_name, dep_city, arival_city, date_month, "
             + "date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats "
             + "FROM flight "
             + "WHERE dep_city = ? AND " 
             + "arival_city = ? AND "
             + "date_month = ?";

    try (PreparedStatement stat = conn.prepareStatement(sql)) {
        stat.setString(1, SearchFlight.getFromCity());
        stat.setString(2, SearchFlight.getToCity());
        stat.setString(3, SearchFlight.getMonth());
        try (ResultSet rs = stat.executeQuery()) {
             jTable1.setModel(DbUtils.resultSetToTableModel(rs));
        }
    }
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • @SherzodElamanov, don't forget to "accept" the answer by clicking on the check mark so people know the problem has been solved. – camickr Nov 26 '15 at 16:14