-2

I have to connect a database to my codes to check a pin code. I have managed to make it but I'm having some problem to make the else part of the if statement to work. I think its the query part which is causing the problem as when I change the if..else statement it works perfectly.

If there is any other way to write this query to get the same result please let me know

thank you


public void getOperation() {


    {       
        Connection conn = null;
        String query = "SELECT pin FROM customerdetails WHERE pin='"+Pin+"'";
        Statement stmt = null;

        try {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/customerdb", "user","@1234@");

            stmt = conn.createStatement();

            ResultSet rs = stmt.executeQuery(query);

            while (rs.next()) {
                String password =  rs.getString("pin");
                if (Pin.equals(password)) {

                     PinCheck = "Pin OK";  
                } else 
                {
                    PinCheck = "Invalid Pin";
                }

            }
        } catch (SQLException e) {
            System.err.println(e);
        } finally {
            if (stmt != null) {

            }
            if (conn != null ) {
                //conn.close();
            }
        }   
    }

J_D
  • 740
  • 8
  • 17
Sanju
  • 1
  • 5

1 Answers1

1

Having this

  String query = "SELECT pin FROM customerdetails WHERE pin='"+Pin+"'";

    while (rs.next()) {
        String password =  rs.getString("pin");
        if (Pin.equals(password)) {

             PinCheck = "Pin OK";  
        } else 
        {
            PinCheck = "Invalid Pin";
        }

    }

makes little sense, as you will always have equal Pin - because you are querying for it. Check for results count. 1== Pin matches, 0== pin invalid.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
  • This query is vulnerable for sql injection see https://stackoverflow.com/questions/4333015/does-the-preparedstatement-avoid-sql-injection – Mike Holtkamp Apr 29 '19 at 13:44
  • Im not getting it, could you please give me an example how to implement this in my code? – Sanju Apr 29 '19 at 16:34
  • You are literally querying "get pin where pin is equal to X" and then you are checking if that Pin is X - well obviously it is. – Antoniossss Apr 29 '19 at 19:52