0

I have saved my data in my MySQL database table. I am using jTextField to take user input. I want to display the rows in jtable where the user input sub-string is a part.

Code I tried:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        try{

            Class.forName("com.mysql.jdbc.Driver");
            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/date","root","");
            String query="SELECT * FROM ok where day like '%=?%'";
            PreparedStatement prepstmt=conn.prepareStatement(query);
           prepstmt.setString(1,jTextField2.getText());   // include this for showing only particular row else remove this line
            ResultSet rs=prepstmt.executeQuery(); 
            jTable1.setModel(DbUtils.resultSetToTableModel(rs));

        }catch(Exception e){

            JOptionPane.showMessageDialog(null, e);
        }

    } 

In my case the substring to be searched is entered by user in jTextField1 and I want to use that user input.

Please correct my **String query=""; **

1 Answers1

1

I believe the library will not replace the ? inside strings. You need to do something like:

String query="SELECT * FROM ok WHERE day LIKE CONCAT('%', ?, '%')";

Alternately you can build the string using Java:

String query="SELECT * FROM ok WHERE day LIKE ?";
PreparedStatement prepstmt = conn.prepareStatement(query);
prepstmt.setString(1, '%' + jTextField2.getText() + '%');

You might want to remove % and _ characters from the user supplied string.

Salman A
  • 262,204
  • 82
  • 430
  • 521