Error when doing email query in the bank

1

I am getting an error in NetBeans when doing a query in a SQL database that validates the user login from the email:

package Modelo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlUsuarios extends Coneccao {

    public boolean registrar(Usuarios usr) throws SQLException {
        PreparedStatement ps = null;
        Connection con = getConeccao();

        String sql = "INSERT INTO usuarios (nome, email, password, id_tipo) VALUES (?,?,?,?)";
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1, usr.getNome());
            ps.setString(2, usr.getEmail());
            ps.setString(3, usr.getPassword());
            ps.setInt(4, usr.getId_tipo());
            ps.execute();
            return true;

        } catch (SQLException ex) {
            Logger.getLogger(SqlUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        };
        return false;
    }

    public boolean login(Usuarios usr) throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection con = getConeccao();

        String sql = "SELECT nome, email, password, id_tipo, FROM usuarios WHERE email like ? ";
        try {
            ps = con.prepareStatement(sql);
            ps.setString(2, usr.getEmail()); // ifnot put '3'
            rs = ps.executeQuery();

            if (rs.next()) 
            {
                if (usr.getPassword().equals(rs.getString(3))) //4º elemento na linha ...= "SELECT id, nome, email, password, id_tipo, FROM ...  
                {
                    //posições na linha está no numero. 


                    usr.setNome(rs.getString(1));
                    usr.setId_tipo(rs.getInt(4));
                    return true;
                } 
                else 
                {
                    return false;
                }

            }
            return false;

        } catch (SQLException ex) {
            Logger.getLogger(SqlUsuarios.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

    }

The error:

  

java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1)

    
asked by anonymous 17.08.2017 / 12:25

1 answer

5

I believe error is on this line:

ps.setString(2, usr.getEmail());

You only pass an argument in the query: "SELECT nome, email, password, id_tipo, FROM usuarios WHERE email like ? " . So it should be 1 ai:

ps.setString(1, usr.getEmail());

I also suggest removing the comma after id_tipo , so as not to give syntax error in mysql.

    
17.08.2017 / 12:34