Doubt with PreparedStatement with INNER JOIN in Java

2

I'm having a question about using PreparedStatement with INNER JOIN, here's my code:

public List<Emprestimo> pesquisar() throws SQLException {

    List<Emprestimo> listaEmprestimo = new ArrayList<Emprestimo>();

    String sql = "SELECT emp.cod_obra AS id_obra, ob.titulo, emp.dispo, emp.dataDevolu  "
            + "FROM emprestimo emp "
            + "INNER JOIN obra ob "
            + "ON ob.cod_obra = emp.cod_obra"
            + "ORDER BY id_obra";

    PreparedStatement ps = c.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();

    listaEmprestimo = new ArrayList<Emprestimo>();

    while (rs.next()) {
        Emprestimo emp = new Emprestimo();
        emp.getObra().setCodObra(rs.getInt("id"));
        emp.getObra().setTitulo(rs.getString("nome"));
        emp.setDisp(rs.getInt("status"));
        emp.setDataDevolucao(rs.getDate("dataDev"));
        listaEmprestimo.add(emp);
    }
    rs.close();
    ps.close();

    return listaEmprestimo;

}

However, when I compile the code this error is returned:

ButwhenIdothequery,itworks.Whatgoeswrong?

    
asked by anonymous 10.06.2016 / 06:58

1 answer

11

Getting this your code snippet exactly as it is:

String sql = "SELECT emp.cod_obra AS id_obra, ob.titulo, emp.dispo, emp.dataDevolu  "
        + "FROM emprestimo emp "
        + "INNER JOIN obra ob "
        + "ON ob.cod_obra = emp.cod_obra"
        + "ORDER BY id_obra";

We get a string like this (without the line break, of course):

SELECT emp.cod_obra AS id_obra, ob.titulo, emp.dispo, emp.dataDevolu  FROM emprestimo emp
INNER JOIN obra ob ON ob.cod_obra = emp.cod_obraORDER BY id_obra";
                                                ↑
      Aqui está o problema, falta um espaço ─ ─ ┘

To fix the mentioned error, change this:

        + "ON ob.cod_obra = emp.cod_obra"

for this

        + "ON ob.cod_obra = emp.cod_obra "

This type of typing error can be detected with a simple print of the generated SQL on the screen.

    
10.06.2016 / 12:41