Search code examples
javamysqlsqljtablejtextfield

Match patterns to an Sql database by using the jtextfield KeyReleased event that automatically updates the jtable


I am trying to automatically update a jtable (Table_world)with database contents using the keyReleased event on the jTextfield (tableQuery).

I am using % feature in mysql to do the pattern matching.

However with no luck i am getting the error java.lang.ArrayIndexOutofBoundsException 0, when i type a single character to the textfield.

Please tell me what's wrong with my code?

I am using Netbeans GUI Builder for this.

Here is my code pls tell me what's wrong with this.

...
import net.proteanit.sql.DbUtils;
....
private void tableQueryKeyReleased(java.awt.event.KeyEvent evt) {        
        try {
        String sql = "select empoyeeid, name, surname, age from empoyeeinfo where name LIKE '%?%';";
        pst=conn.prepareStatement(sql);
        pst.setString(1, tableQuery.getText());
        rs = pst.executeQuery();
        Table_world.setModel(DbUtils.resultSetToTableModel(rs));
        }
        catch(Exception e) {
        JOptionPane.showMessageDialog(null, e);
        } finally {
            try {
                rs.close();
                pst.close();
            } catch(Exception e) {

            }
        }
    }     

Solution

  • You need to set the "%" in the setString method. Like this:

    pst.setString(1, "%" + yourString +"%");