Query ORDER BY dynamic from the selection of a comboBox

1

I'm developing an application in java that manages a database. This application primarily performs a SELECT database, then submits ResultSet to an editable table.

I tried to add a comboBox to the user to select the order in which to list the data, but the code segment I wrote for this effect is not working.

My question is whether there is any way to work around this problem and do some sort of concatenation of strings and variables so that the ORDER BY parameter is dynamic and dependent on what the user chooses.

else if (Item == 1)
{ /* Computer List) */
    comboBoxOrderBy.setModel(new DefaultComboBoxModel(new String[] { "computer_id", "cpu_model",
        "cpu_clock", "ram", "hdd", "os", "archit", "computer_name", "computer_type",
    "computer_brand", "computer_model", "serial_number", "status" }));
    comboBoxOrderBy.addActionListener(
    new ActionListener()
    { /*
        * ACÇAO DA CAIXA
        * ORDER BY
        */
        public void actionPerformed(ActionEvent arg0)
        {
            String teste = (String)comboBoxOrderBy.getSelectedItem();
            JOptionPane.showMessageDialog(frmInventoryDatabaseManager, teste);
            try
            {
                /*
                * BEGINING OF DATABASE REQUEST
                */
                Connection lig = DriverManager.getConnection(
                "jdbc:mysql://localhost/inventorydb", "root", "");
                PreparedStatement inst = lig.prepareStatement(
                "SELECT computer_id, cpu_model, cpu_clock, ram, hdd, "
                + "os, archit, computer_name, computer_type, computer_brand, "
                + "computer_model, serial_number, status FROM computerlist ORDER BY ? ASC");
                inst.setString(1, teste);
                ResultSet rs = inst.executeQuery();
                table1.setModel(DbUtils.resultSetToTableModel(rs));
                lig.close();
                /*
                * END OF DATABASE REQUEST
                * SERVICES
                */
            }
            catch (SQLException e1)
            {
                JOptionPane.showMessageDialog(frmInventoryDatabaseManager,
                "Impossivel ligar á base de dados: "
                + e1.getLocalizedMessage());
            }
        }
    });
}
    
asked by anonymous 04.05.2016 / 11:57

1 answer

1

As the goal is to sort the table according to the column, just activate the rowSorter , through the command:

suaTable.setAutoCreateRowSorter(true);

As a result, the columns become "organizables". Remember that if you use% s of your own%, you need to identify the data types of each column using the TableModel method to work correctly (if any column is of some kind of class you created).

    
04.05.2016 / 16:18