How to take more than one database value and save in a Combobox more than one returned value?

Asked

Viewed 102 times

1

I have a question that is next, when I make a bank consultation he can return me more than two names, and I can only get one. The idea is to filter the names of doctors by the type of doctor(Neurosurgeon, among others) and then take these names and put in a Combobox.

Here is the code but returns only one name.

I created a function for that.

    public String tipoMedico(String tipo)
    {
    try{
    Statement comando = cone.createStatement();
    ResultSet rs = comando.executeQuery("SELECT Nome,Tipo FROM `medicos`                    
    WHERE Tipo='"+tipo+"';");//Se tiver dois médicos do mesmo tipo, era  
    para retornar mais de um nome, quero saber como pegar todos os nomes  
    que retornar.

    while(rs.next()) {

              String Tipo = rs.getString("Tipo");
                String Nome1 = rs.getString("Nome");

                if(tipo.equals(Tipo)){                    

                 return Nome1;
                  }
    }}
    catch(SQLException e)
    {
      JOptionPane.showMessageDialog(null,"Erro na Conexão com o Banco de 
    Dados");
    }
     return "Não encontrado";
    }

Then call Names in a Combobox.

   private void cbTipoActionPerformed(java.awt.event.ActionEvent evt) {   
   String nome =  
   dado.tipoMedico(cbTipo.getItemAt(cbTipo.getSelectedIndex()));
   String tipo = cbTipo.getItemAt(cbTipo.getSelectedIndex());
    switch(tipo)
   {
    case "Neurocirurgião": cbDoutor.removeAllItems();
    cbDoutor.addItem(nome);//Aqui eu adiciono o nome retornado do banco   
    na comboBox
      break;
      case "Clinico Geral": cbDoutor.removeAllItems();
       cbDoutor.addItem(nome);
      break;

     }}
  • Dude, the problem is in your Turn. You’re familiar with the structure LIst?

  • You are returning a simple string from the database. A combobox expects a combomodel or string array.

  • Another thing, you should not mix the layers, wherever it is to search in the bank, it should be only for consultation and bank functions, optionpane in the bank method and with defined return is a bad practice.

1 answer

2


Your problem is that you return in the first increment of ResultSet. Then I suggest you return one List of String:

public List<String> tipoMedico(String tipo) {
List<String> medicos = new ArrayList<>();

try {
  Statement comando = cone.createStatement();
  ResultSet rs = comando.executeQuery("SELECT Nome,Tipo FROM `medicos` WHERE Tipo ='" + tipo + "'  ;");

  while (rs.next()) {
    String tipoEncontrado = rs.getString("Tipo");
    String nome = rs.getString("Nome");

    if (tipoEncontrado.equals(tipoEncontrado)) {
      medicos.add(nome);
    }
  }
} catch (SQLException e) {
  JOptionPane.showMessageDialog(null, "Erro na Conexão com o Banco de Dados");
}

return medicos;

}

And add the result to the combo as follows:

private void cbTipoActionPerformed(java.awt.event.ActionEvent evt) {
  List<String> nomes = dado.tipoMedico(cbTipo.getItemAt(cbTipo.getSelectedIndex()));
  String tipo = cbTipo.getItemAt(cbTipo.getSelectedIndex());

  cbDoutor.removeAllItems();

  for (String nome : nomes) {
    cbDoutor.addItem(nome);
  }
}
  • What is the idea of giving -1 in this reply and neither leave a comment on what can be improved or what theoretically is wrong?

  • Thank you very much Thank you very much, I will try here, While to the Diegofm our guy thanks for the tip, I created a class own pro bank yes, but I did not know this of the Joptionpane thank you very much, Then I return with the result Thanks Sorack

  • Don’t forget to mark e+1 (useful) if this solution suits you, so it can be used as a solution for other people as well!

  • It was successful to list more than 1 value, but now this with a problem, every time I select a type in the check box he is adding the same name again, if I select neurosurgeon 2x is appearing the names in double

  • You are giving removeAllItens before adding?

  • @Has Andersonhenrique ever considered creating a comboboxmodel based on a medical class? It’s not complicated and makes your code more organized.

  • That’s right I forgot about removeAllItens, thank you very much I will mark here, where do you mark it? I am new here, created today

  • Next to the answer. If you want better code quality you can create a model as @diegofm commented and also separate the classes. Ah, in your original example had variables starting with uppercase letter, by the old Sun convention you should always start variable names with lowercase letter

  • @diegofm so dude, I’m at the beginning of java in college, there’s a lot of things I don’t know, to tell you the truth most of what I already know I learned on the internet anyway

  • 1

    @Andersonhenrique understand, but the tip is, always try to separate the responsibilities, for example, in this code, I would have a Medical class and another for specialty, usually the relationship of doctor to specialty is nxn(doctors can have several specialties, and vice versa).

Show 5 more comments

Browser other questions tagged

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