Error using LIKE to search by name

Asked

Viewed 334 times

3

When I used Mysql I could use the LIKE ? to do searches by name, code, etc... Now in SQL Server I’m not getting.

I have a Textfield and a search button, I want to take the value of textField and move on to the search. I’m trying to do it this way:

StringBuilder sql = new StringBuilder();
        sql.append("SELECT\n"
                + " Contrato.AutoId                         AS                Contrato_ID,\n"
                + " Contrato.Codigo                         AS                Codigo_contrato,\n"
                + " Pessoa.Nome                             AS                Contratante,\n"
                + " SuspensaoVinculo.VinculoRescindido      AS                Vinculo_rescindido,\n"
                + " SuspensaoVinculo.DataSuspensao          AS                Data_suspencao,\n"
                + " SuspensaoVinculo.DataReativacao         AS                Data_reativacao ");
        sql.append("FROM Contrato                           WITH (NOLOCK)\n"
                + " INNER JOIN Pessoa                       WITH(NOLOCK) ON Contrato.Contratante = Pessoa.AutoId\n"
                + " LEFT JOIN SuspensaoVinculo              WITH(NOLOCK) ON SuspensaoVinculo.Contrato = Contrato.AutoId ");
        sql.append("WHERE\n"
                + " Pessoa.Tipo             =   2 "
                + "     Pessoa.Nome LIKE ? ");
        sql.append("ORDER BY Pessoa.Nome ");

        /* Abre a conexão */
        Connection conn = Conexao.abrir();

        /* Mapeamento objeto relacional */
        PreparedStatement comando = conn.prepareStatement(sql.toString());
        comando.setString(1, "%" + c.getContratante() + "%"); 
        ....

And in my view I recover that way:

private void atualizarInicial() {
        Cadastros cadastros = new Cadastros();
        ConsultaCadastro consulta = new ConsultaCadastro();
        List<Cadastros> lista;
        try {
            cadastros.setContratante(pesquisar.getText());
            lista = consulta.buscar(cadastros);
            tblCadastros.setItems(FXCollections.observableArrayList(lista));
            ...

That is the exception:

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near 'Contrato'.

3 answers

4


An AND is missing

"WHERE\n"
+ " Pessoa.Tipo             =   2 **AND**"
+ "     Pessoa.Nome LIKE ? ");
  • 1

    Our truth, I forgot about AND and was killing me kk. Thank you

1

Check in this part the lack of an "AND" (or other operator) which may be the source of your error:

sql.append("WHERE\n" 
           + " Pessoa.Tipo             =   2"
           + "  AND   Pessoa.Nome LIKE ? ");

1

In addition to AND after Pessoa.tipo try to add simple quotes in LIKE, SQL uses so:

comando.setString(1, "'%" + c.getContratante() + "%'");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.