Java - how to compare user's input with Microsoft Access database

Hello,

I need your help with this Java program. I'm trying to read the input from the keyboard and compare it to the data queried from the MS Access database. I was able to query the database and display it; however, I'm having problems getting the user's input (from the keyboard) to compare it with the database. Goal: If the user's input matches with the database, then displays the result. If the user's input does not match, display "Sorry, No record found). Thanks in advance.

HERE IS MY PROGRAM:

//output.java

      import java.sql.*;
     
        public class jdbc_test  {

        Connection con;
        String query = "SELECT CustomerID FROM Customers";
        Statement stmt;
        ResultSet rs;
        String input;
      String [] values;
       
        public jdbc_test()
       {
      try {
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           con = DriverManager.getConnection("jdbc:odbc:project");
          }
              catch(java.lang.ClassNotFoundException e)
             {
           System.err.print("ClassNotFoundException: ");
           System.err.println(e.getMessage());
          }

              catch(SQLException ex)
             {
          System.err.print("SQLException: ");
          System.err.println(ex.getMessage());
          }

       } //end of public jdbc_test()

          // Read input from the keyboard
          public void readScan()      throws Exception
              {
                     System.out.println("Please Scan Your Membership Card: ");                            
                     BufferedReader a = new BufferedReader (new InputStreamReader (System.in));                 
                          input = a.readLine();
          }
         
            // compare input with data queried
               public void compare() throws Exception
            {
                  for(int j=0; j<10; j++)
               {
               
               // display the data if input matches with data queried
                  if (input == values[j])
                   {
                        getValues();
                        result();
                   }
                  
                  else
                   {
                        System.out.println("SORRY, NO RECORD FOUND");
                   }
               }
            }                          
        
         // get data from Microsoft Access database
       public String [] getValues()
      {
       String [] myresponse = null;
     
      try
         {
         myresponse = new String[10];  // for now lets just keep 10 slots
           stmt = con.createStatement();                                          
           rs = stmt.executeQuery(query);

         int i = 0;
         while(rs.next())
         {
            myresponse[i] = rs.getString("CustomerID");
            i++;          
          }
           }
         catch( Exception e )
          {
            myresponse = null;
          }
         return myresponse;  
       }//end of getValues
        
        
          public void close()
       {
           try
           {
              con.close();
             }
      
           catch ( Exception e ) {};
       }
               
            // display results if input matches data queried
         public void result()            throws Exception
            {
        System.out.println("Here are the values:");
        jdbc_test connection = new jdbc_test();
       
        values = connection.getValues();
        for (int i = 0; i < values.length; i++)
            {
          System.out.println(values[i]);
         }
        connection.close();
        }
     }

       // functions calling
       public void functions()      throws Exception
            {
                  readScan();
                  compare();
                  close();
            }  
}  
                 
  public class output
      {
            
      public static void main(String args[]) throws Exception
        {                 
       
                jdbc_test func = new jdbc_test();
                func.functions();
                
               }
      }
Khanh_huuAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Tommy BraasCommented:
You need to modify:

   if (input == values[j]) {

to:

   if (input.equals(values[j])) {

The equals sign for object types in Java compares the references for equality, not the actual contents of the objects the references point to.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Giant2Commented:
Agree with orangehead911 told (input == values[j] is wrong).
But I point your attention to a program structure.
Why you make the control with code and not restrict your query to select only record valid for your compare?
In this manner you can sold many computing-time because all the read not needed are removed directly from the DBMS.
It's only a suggest.

Bye, Giant.
Manikandan ThiagarajanSenior consultantCommented:
i agree with giant, your  make attention yourprogram structure
 if (input == values[j])
                {
                    getValues();
                    result();
                }
               
               else
                {
                    System.out.println("SORRY, NO RECORD FOUND");
                }
             }


          }                      
get values return string where you store it in varialb

in result  method only  youget the value from database using values variable.

befofre compare   like if (input == values[j])
                {
                    getValues();
                    result();
                }
               
            where you call the result method and get the value from database.


  public void compare() throws Exception
          {

            result();

//you call the result method here
               for(int j=0; j<10; j++)
             {
                               
             // display the data if input matches with data queried
               if (input .equals( values[j])
                {

               System.out.println(input)

                  System.out.println(values[j]);
                 //   getValues();
                   // result();

//this get Values() and result() method is not required here
                }
               
               else
                {
                    System.out.println("SORRY, NO RECORD FOUND");
                }
             }
          }                

as per      


Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

mjzalewskiCommented:
I guess your program is printing out the message SORRY, NO RECORD FOUND multiple times. That's because you execute the body of the loop for each CustId value you retrieved from the database. Almost all the values don't match the input, so you get the error message multiple times.

My guess is that .equals vs == would make no difference. The other posters are correct that you should use .equals to compare the value of two String objects. But that won't correct the logic of your program. You may even find in this simple case that == works fine. However, it will not work consistently.


Instead of trying to retrieve all the CustomerIDs from the database, it would be far better if you asked the database if the scanned input matches any customer ID. (This is what giant2 has suggested)


Here is how to do it:
You could do this with a PreparedStatement. The following code snippet gives the idea

  // Create a prepared statement to select the matching row. Use a ? for the variable part
  PreparedStatement psCheckCustId = conn.prepareStatement(
    "SELECT custId FROM Customers WHERE custId=?"
  );

  // Bind your input variable to the ?, then execute the prepared statement
  psCheckCustId.setString( 1, input);
  ResultSet rsCheckCustId = psCheckCustId.executeQuery();

  // If rs.next() returns false, it means the query returned 0 rows. Otherwise, it returned 1 row matching the input
  boolean bMatch = rsCheckCustId.next();

  // Release the resources acquired from the database
  rsCheckCustId.close();
  psCheckCustId.close();
  conn.close();

  // At this point, bMatch == true if there was a matching row in the database. bMatch == false if there was no match
  if( !bMatch) {
     System.out.println( "SORRY, NO RECORD FOUND");
  }
Khanh_huuAuthor Commented:
Not much help, but awarded the points.
Giant2Commented:
>Not much help,...
You could answer to our post.
About the accepting, it's little strange.
orangehead911 tol something,
Giant2 told: Agree with orangehead911...
stmani2005 told: i agree with giant...

Why accepting this last one?
Khanh_huuAuthor Commented:
I do apologize, I'm new to this; therefore, I didn't know I can split up the points.
Tommy BraasCommented:
;-D
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.