Search code examples
javamysqljcreator

java Parameter index out of range (1 > number of parameters, which is 0 with mysql - simple login


Im trying to check a username and password in Java (in j creator) but cant get the syntax right. How do I implement a simple check in the database by passing username and password? Here is the code thats gicing me the problems:

      try
    {
String userN, passW, host, database;
userN = "Michael";
passW = "Blaine22";
host = "localhost";
database = "maintenance_work";

        Connection conn = DriverManager.getConnection
    ("jdbc:mysql://"+host+":3306/"+database, userN, passW);

    conn.setAutoCommit(false);
    ResultSet rs = null;
    PreparedStatement pst = null;

    Boolean user_Check_pass;

    String sql =("SELECT * from operators where user_name = " + user + " and pass_word= " + pass);

        pst = conn.prepareStatement(sql);

        pst.setString(1, user);
        pst.setString(2, pass);
        rs = pst.executeQuery();

        if (rs.next())
        {
             System.out.println ("Username and Password correct");
             user_Check_pass = true;
        }
        else
        {
              System.out.println ("invalid username and password");
               user_Check_pass = false;
        }
    }
   catch (SQLException e)
   {
    e.printStackTrace();
}
    return false;

Solution

  • I just needed to change the SQL query string to below in order to pass the parameters! Doh!

    String sql = "SELECT * from operators where user_name = ? and pass_word = ?";