开发者

Message dialog displaying at improper time

开发者 https://www.devze.com 2023-02-22 18:36 出处:网络
I have a searchform. In this I am searching the name alphabetically when I enter the alphabet in textbox and if there is any name from that alphabet in my DB than it shows the message that record foun

I have a searchform. In this I am searching the name alphabetically when I enter the alphabet in textbox and if there is any name from that alphabet in my DB than it shows the message that record found (on click of search button) but when I enter a letter from which there is not any name starting with that letter even than it showing message "record found."

My code is:

if(searchby.equals("Name"))

        {
             try
            {

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            System.out.println("\n Driver loaded");
            Connection con=DriverManager.getConnection("jdbc:odbc:wanisamajDB");

             Statement stmt=con.createStatement();



            ResultSet rs = stmt.executeQuery("SELECT * FROM FAMILYcensus WHERE Name LIKE '"+ tfsearch.getText()+"%'ORDER BY Name ASC");

             StringBuilder sb = new StringBuilder();
             while (rs.next()) {

             String name = rs.getString("Name");
             sb.append(name + System.getProperty("line.separator") );
             }
             String names = s开发者_StackOverflowb.toString().trim();


           JOptionPane.showMessageDialog(null, "RECORD FOUND");
           con.close();
           tasearch.setText(names);


           //con.close();

         }
            catch(SQLException eM)
          {
            JOptionPane.showMessageDialog(null,"INVALID RECORD");
           }
          catch(Exception et)
           {
             System.out.println("error:"+et.getMessage());
            }  


Your code is neither checking whether rs is empty, nor setting things up as if the search has failed before iterating over rs. An empty result from SELECT doesn't produce an exception.

If there is nothing in the RecordSet then you should do to your form whatever you want to do to indicate that no records were found.


Well, you never check to see if your query returned anything or not.

Do that, and act accordingly when there's no results.

Edit: MByD makes a really good point in his direct comment to your question. You don't seem to understand the basic concepts of "If - then - else" given the questions you're posting on SO. Copying and pasting code from examples without understanding what you're doing may not be the best way for you to learn how to program. A good basic intro to programming book may be a valuable investment.


It looks like unless an exception is thrown, you'll get that message. Maybe test it like

if(sb.length()==0) JOptionPane.showMessageDialog(null, "NO RECORD FOUND");
else JOptionPane.showMessageDialog(null, "RECORD FOUND");
0

精彩评论

暂无评论...
验证码 换一张
取 消