How to search Data in jTable using MS Acess using ComboBox with jTextField Netbeans

1.1k Views Asked by At

In my program I can search data in jTable with this code using jTextfield "txtsearch" in my program.

Please take a look at my actual program. Here is a picture:

https://i.stack.imgur.com/QZguC.png

This is my code in jTextField "txtsearch". In this code I can search the jTable via Name only. I want to search by using the jComboBox.

String a=txtsearch.getText();
conn=MyConnection.ConnectDB();
String sql="Select* from StdRecord WHERE Name LIKE'"+a+"%'";
try{
    pst=conn.prepareStatement(sql);
    rst=pst.executeQuery();
    jTable1.setModel(DbUtils.resultSetToTableModel(rst));
}catch(Exception e){}

Also, based on the image that I have uploaded, my question is: How can I search student by Name, MiddleName and Surname using the combo box? For Example, I select MiddleName in the combo box, then when I type in the jTextField "txtsearch" I can only search in MiddleName part of the table.

1

There are 1 best solutions below

3
camickr On BEST ANSWER

This is my code in jTextField "txtsearch". In this code I can search the jTable via Name only. I want to search by using the jComboBox.

Your current SQL uses a variable for the data you want to search for so why can't you use a variable for the column you want to search?

String a=txtsearch.getText();
String column = comboBox.getSelectedItem().toString();
String sql="Select* from StdRecord WHERE " + column + "LIKE'"+a+"%'";

Also, to make the SQL a little easier to code and maintain you should use a PreparedStatement:

String sql = "Select* from StdRecord WHERE " + column + "LIKE ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, a + "%" );
stmt.executeQuery();