1
I’m trying to build a Java function pesquisarCliente
where it must be consulted in the Database whether it exists or not. If there is more than one result you should return all records, if you do not find anything you should return a warning to the user.
Using the while
it brings me all the records as the search, but I could not validate when it does not find anything. If I use only the if
it works, validates if the record exists or not, but presents a single record. I tried to make the combination of the while
and of if
, unsuccessful.
public String pesquisarCliente(String pesquisarCliente) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER).newInstance();
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
Scanner ler = new Scanner(System.in);
System.out.println("Nome Cliente: ");
pesquisarCliente = ler.nextLine();
String sql = "SELECT cpf_cnpj,nome_rs,ativo FROM tb_cliente WHERE (cpf_cnpj ='" + pesquisarCliente + "' AND ativo = 1) OR (nome_rs LIKE '%" + pesquisarCliente + "%' AND ativo = 1)";
ResultSet result = stmt.executeQuery(sql);
if(result.next()){ // Dúvida <===
while (result.next()) {
String cpfclient = result.getString("cpf_cnpj");
int status = result.getInt("ativo");
String nomeclient = result.getString("nome_rs");
// Display valores
System.out.print("CPF/CNPJ: " + cpfclient);
System.out.print("\t Nome: " + nomeclient);
System.out.println("\n=====================\n");
PreparedStatement upgradeTempGeralCliente = conn.prepareStatement("UPDATE tb_temp_geral SET [cpf_cnpj_Cliente] = '"+cpfclient+"', [nome_client]= '"+nomeclient+"' WHERE [id] = 1;");
upgradeTempGeralCliente.executeUpdate();
this.setNomeCliente(nomeclient);
this.setCpfCliente(cpfclient);
}
}else{
System.out.println("NÃO achei o cliente!");
}
result.close();
stmt.close();
conn.close();
//ler.close();
} catch (Exception e) {
}
return null;
}
I realized that on the line if(result.next()){ // Dúvida <===
if I replace result.next()
by anything that is true (for example, if(funciona == true)
) he enters the while
normally.
I think the mistake is in using the result.next()
within the if
. But how to get the search return to return the message "I DIDN’T FIND THE CLIENT!"?