从postgresql填充jTable

时间:2015-11-26 11:05:43

标签: java database swing postgresql jtable

我正在使用数据库和GUI在NetBeans 8中进行java项目。当我搜索数据库并将找到的值添加到JTable时出现问题:所有值都只添加到JTable的第一列,而我需要添加它们分别对应相应的列。我尝试了getColumnCount(),它也给了我一个意思,我只有一列。如何将数据库值添加到JTable的相应列?

我已经尝试了here

提出的所有填充功能

我的代码:

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是一个GUI类,其方法返回在GUI中获取的字符串。 DbUtils.resultSetToTableModel(rs)是net.proteanit.sql.DbUtils中的一个方法;

因此,预计数据将被填充到9列中,并且它将所有数据填充到一列中。

1 个答案:

答案 0 :(得分:2)

SELECT ( ... )

必须是

SELECT .... 

最好按预期使用PreparedStatement。否则SQL injection仍然是可能的。尝试使用资源可以在所有情况下关闭事物。

    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));
        }
    }