SAVE DATA FROM A COMBO BOX TO MYSQL

0

I will comment on the problem I have. I have a ComboBox in Java which is connected to a BD (Mysql). The ComboBox loads perfectly the data of the BD, in this case the name of some users. However, when I programmed the 'Save' button I do not know how to save the Item I selected in the ComboBox to the Database ..

This is the code that loads the data of the BD

modeloCombo = new DefaultComboBoxModel(new String [] {});
    initComponents();
    //Instancion al clase productos
    productos objproductos = new productos();

    //ResultSet
    ResultSet estados;
    //Instancio la clase estados
    estados = objproductos.consultarEstado();
    try {
        //Recorremos el resultado generado por la consulta
        while(estados.next()){
            //Con el metodo addElement vamos a agregar cada resultado al comboBox
            modeloCombo.addElement(new Estado(estados.getInt("nit"), estados.getString("nombre")));                
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null,"Consulta no hecha"+e.getMessage());
    } 

This is the object that I use every time I need the ComboBox (This button is inside the program)

//Creamos un objeto
    Estado objEstado = (Estado) cboEstado.getSelectedItem();
    //Asignamos el atributo del objeto seleccionado en el combo.
    int estado = objEstado.getNit(); //Ya aquí tenemos el id del estado seleccionado.

 int provedores_nit;
 //En el if de abajo estoy seleccionando el ID del objeto y luego asignandoselo a la variable provedores_nit para luego guardarlo en la BD
 if(cboEstado.getSelectedItem() ==  objEstado.getNit()){
        provedores_nit = objEstado.getNit();
    }
    
asked by Permomo 08.11.2018 в 23:36
source

1 answer

0

It's very simple, you must first have the name of your combobox, let's say this example

name of the combobox: cbDocumentos

We create a variable of type String: cb_documents

Now to get the selected item you must do this

String documentos_cb;

documentos_cb = cbDocumentos.getSelectedItem().ToString();

Here you are sending the selected item from the combobox to the variale documentos_cb

at the time of doing the update or insert, in the index of the table simply place the variable documentos_cb

Something like that, because I'm assuming, but I'll leave this example with an insert:

pstIngresarDatos.setString(8, documentos_cb);

and good for an update, it would be the same:)

 pstUpdateDatos.setString(8, documentos_cb);

I hope I have helped you: D

    
answered by 09.11.2018 / 15:17
source