Skip to main content
4 de 6
se añadieron 39 caracteres en el cuerpo
Tygreton
  • 833
  • 4
  • 21

Error de Sintaxis - Select en Java

Deberá ser una tontería pero llevo un rato bueno detrás y no consigo arreglarlo. ¿El select esta bien hecho verdad?

public static boolean login(String user_name, String password) {

    boolean status = false;
    int size = 0;

    String sql = "SELECT * FROM users WHERE userName LIKE ? and password LIKE ?";

    Conexion conexion = new Conexion();
    PreparedStatement preparedStatement;
    ResultSet rs;

    try {
        preparedStatement = conexion.getConexion().prepareStatement(sql);
        preparedStatement.setString(1, user_name);
        preparedStatement.setString(2, password);
        
        System.out.println(preparedStatement);

        rs = preparedStatement.executeQuery(sql);

        if (rs != null) {
            rs.last(); 
            size = rs.getRow();
        }

        status = (size == 1);

        preparedStatement.close();
        conexion.cerrarConexion();

        return status;

    } catch (SQLException e) {
        System.out.println(e);
        return false;
    }

}

ERROR #1

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? and password LIKE ?' at line 1

Si uso:

String sql = "SELECT * FROM users WHERE userName = '?' and password = '?'";

ERROR #2

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

Si uso:

preparedStatement.setString(1, "%"+user_name+"%");
preparedStatement.setString(2, "%"+password+"%");

ERROR #1 con un sout de la consulta.

SELECT * FROM users WHERE userName = ? and password = ? ------ com.mysql.jdbc.JDBC4PreparedStatement@7b0636ec: SELECT * FROM users WHERE userName = '%jjh%' and password = '%sdf%'

ERROR:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? and password = ?' at line 1
Tygreton
  • 833
  • 4
  • 21