Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created a java software application in which there is a form and that contains few JTextField and one JList. The items in the JList is also inserted by the user with the help of a JTextField present in the same page. I want to save the JTextField and the JList in MySQL database on clicking the submit button. I have successfully inserted the JTextField data in MySQL database table but the problem is that I don't know how to save JList in single block . Just to practice, I have tried to save JList and its taking new row for each item in the database.

Is there any way I can add the entire JList in single block.

OR

If not how can I link the JList with the remaining data in MySQL.

I know we can ask only one question at a time but the other problem is how to retrieve JList from the database to JTable in the form of JList within the JTable with all other details.

What I have tried:

Java
    DefaultListModel dlm= new DefaultListModel();
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        String userInput= jTextField1.getText();
        dlm.addElement(userInput);
        jList1.setModel(dlm);
        jTextField1.setText(null);  

    }                                        

String item="";
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

       for(int i = 0; i < jList1.getModel().getSize(); i++)
       {         item = (String)jList1.getModel().getElementAt(i);
        try{

                    Class.forName("com.mysql.jdbc.Driver");
                    Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/a","root","");
                    PreparedStatement stmt = conn.prepareStatement("insert into listt (listitem) values (?)");
                    stmt.setString(1,item);
                    stmt.execute();
                    conn.close();
        }
catch(Exception e){
                    JOptionPane.showMessageDialog(null, e);
                    e.printStackTrace();
                }       
       } 
       JOptionPane.showMessageDialog(null, "Done");
    }  

The above code has two buttons btn1 is adding JTextField data to JList and btn2 is adding the JList item to database. Its saving each item in new row in the database but I want to save it in a single row in a single block with other data.
Posted
Updated 3-Oct-19 14:13pm
v2
Comments
Richard MacCutchan 22-Jul-19 4:43am    
That is the correct way to do it. To read it back you just reverse the process, read each item from the listt table and add it to a new JList.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900