Wannabe JavaGeek Wannabe JavaGeek - 3 months ago 10x
SQL Question

Search the MYSQL Database filtering using either first name or last name typed in JTextfield on JTable

I want to use either last name or first name to filter result shown on JTable from the database such that when i type either Nikola or Tesla in the JTextfield, the row with either of the names is filtered.

I have stored name as one field in the database i.e 'Nikola Tesla' when i type Nikola, it is working right and when i type Tesla it shows no result.

I have one field for name that stores both names.

I don't want to have separate First_Name and Last_Name field.

Please suggest what i should add on my code shown below:

private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {

try {
String selected = (String) jComboBoxSelected.getSelectedItem();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
+ "employee_certificate", "root", "");

String sql = "SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n"
+ "certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+ "WHERE " + selected + " LIKE ? ORDER BY stuff.Emp_Name\n";

PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, jTextFieldSearch.getText() + "%");
ResultSet rs = pstmt.executeQuery();

} catch (Exception ex) {


You need to add % before the jTextFieldSearch.getText() also. See below

pstmt.setString(1, "%" + jTextFieldSearch.getText() + "%");