简体   繁体   中英

Populate jTable from Postgres database

I am new to java swing, so don't mind if it's a very basic question.

The task is to get data from PostgreSQL database and populate it to jTable . I follow the example Example . But there is still something missing. I am receiving data in console from the database but not in the table. Here is the code

DefaultTableModel model_search=DefaultTableModel)jTable_Search.getModel();
String connection_string="jdbc:postgresql://"+host_db+":"+port_db+"/"+name_db+"";

    try(Connection connection = DriverManager.getConnection(connection_string,username_db, password_db)) {
        Statement statement = connection.createStatement();
        String sql_beacons="query to database";
        ResultSet resultSet_beacons = statement.executeQuery(sql_beacons);
        ResultSetMetaData metaData = resultSet_beacons.getMetaData();
        int columns = metaData.getColumnCount();
        while (resultSet_beacons.next()){
           System.out.printf(resultSet_beacons.getString("mac")+" ");
           Object[] objects = new Object[]{resultSet_beacons.getString("mac")};
           model_search.addRow(objects);  
        }                                                 
    }

Download and include the library from http://technojeeves.com/index.php/22-resultset-to-tablemodel

In your code, this statment will populate data to jTable.

String sql="Query to database";
ResultSet rs = stat.executeQuery(sql); 
jTable_Search.setModel(DbUtils.resultSetToTableModel(rs));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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