-2

when I tried to run a SELECT on MySQL through java application, I got the message of syntax error.

Already tried to run this query on MySQL Workbench and it works normally.

Error:

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1

There is my code:

try {
        String sql = "SELECT CPF_USUARIO, NOME_USUARIO, LOGIN, "
                + "DATA_NASCIMENTO, EMAIL, CELULAR_USUARIO, "
                + "DATA_CADASTRO, HORA_CADASTRO, GENERO "
                + "FROM TICKETERIA.TB_USUARIO "
                + "WHERE CPF_USUARIO = ?;";
        
        pstmt = conn.prepareStatement(sql);
        pstmt.setLong(1, cpfUsuario);
        System.out.println(pstmt);
        ResultSet rs = pstmt.executeQuery(sql);
        Usuario usuarioResult = null;
        
        while(rs.next()) {
            usuarioResult = new Usuario();
            usuarioResult.setCpfUsuario(rs.getLong("CPF_USUARIO"));
            usuarioResult.setNomeUsuario(rs.getString("NOME_USUARIO"));
            usuarioResult.setLogin(rs.getString("LOGIN"));
            usuarioResult.setEmail(rs.getString("EMAIL"));
            usuarioResult.setCelular(rs.getString("CELULAR"));
            usuarioResult.setGeneroUsuario(rs.getString("GENERO"));
            usuarioResult.setHoraCadastroStr(rs.getString("HORA_CADASTRO"));
            
            Date dataAux = rs.getDate("DATA_NASCIMENTO");
            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            usuarioResult.setNascimentoStr(df.format(dataAux));
            
            dataAux = rs.getDate("DATA_CADASTRO");
            usuarioResult.setDataCadastroStr(df.format(dataAux));
        }
        return usuarioResult;
    } catch (SQLException e) {
        e.printStackTrace(System.err);
        System.err.println("SQLState: " + ((SQLException) e).getSQLState());
        System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
        System.err.println("Message: " + e.getMessage());
        Throwable t = e.getCause();
        while (t != null) {
            System.out.println("Cause: " + t);
            t = t.getCause();
        }
        return null;
    }
} 
vaibhavsahu
  • 612
  • 2
  • 7
  • 19

1 Answers1

2

The correct call is .executeQuery();. No arguments. You're asking the db to execute the literal query, WITH the question mark, without applying the .setLong` part of it.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72