Search code examples
javamysqlresultset

Column result doesn't as be expected


Here i have query to join two table and merge it into one result by using this query

String query = "SELECT * FROM tb_barang RIGHT JOIN tb_jenis ON tb_barang.kd_jenis = tb_jenis.kd_jenis ";

And here is my table structures for both of tables

Table "tb_barang"
https://i.sstatic.net/6OpeC.png

And Table "tb_jenis"
https://i.sstatic.net/UhLty.png

I was expecting the output like this
https://i.sstatic.net/zhtHx.png

However, when I take column "jenis", java throw exception into it because either out of range or column not found.

Then i check whether the column is exist or not using :

ResultSet resTabel = new mysqlDriver().getKolomBarangList();
            ResultSetMetaData metaData = resTabel.getMetaData();
            int colCount = metaData.getColumnCount();
            if (resTabel.next()) {
        for (int i = 1; i <= colCount; i++) {
        System.out.println("Col(" + i + ") '" + metaData.getColumnName(i) + "' value:" + resTabel.getString(i));
    }

The output:

Col(1) 'kd_barang' value:BAR0000
Col(2) 'nama_barang' value:A
Col(3) 'kd_jenis' value:J_1
Col(4) 'jumlah_barang' value:1
Col(5) 'harga_satuan' value:1
BUILD SUCCESSFUL (total time: 35 seconds)

How to achieve this? Thanks for response


Solution

  • Apparently, i was miss type the method name thanks to @forpas. the getKolomBarangList() refer to field name of table tb_barang and not executing "JOIN" clauses

    protected ResultSet getBarangList()throws SQLException, NullPointerException, ClassNotFoundException{
            String query = "SELECT * FROM tb_barang RIGHT JOIN tb_jenis ON tb_barang.kd_jenis = tb_jenis.kd_jenis ";
            if(resForListBarang == null){
                resForListBarang = alwaysDoResultSet(query);
            }
            return resForListBarang;
        }
    
        protected ResultSet getKolomBarangList() throws SQLException, Exception{
            String query = "SELECT * FROM tb_barang";
            if(getBarangKolom == null){
                getBarangKolom = alwaysDoResultSet(query);
            }
            return getBarangKolom;
        }
    

    And the output for getBarangList() was expected as the final result

    Col(1) 'kd_barang' value:BAR0000
    Col(2) 'nama_barang' value:A
    Col(3) 'kd_jenis' value:J_1
    Col(4) 'jumlah_barang' value:1
    Col(5) 'harga_satuan' value:1
    Col(6) 'kd_jenis' value:J_1
    Col(7) 'jenis' value:Pakan Hewan
    BUILD SUCCESSFUL (total time: 21 seconds)
    

    Thanks to anyone who helping me out :)