how to fill a jtable from sql

1

I have a graphical interface that includes a jtable, at the time of registering, it runs normally, only in the jtable it shows me what I have registered repeatedly but in the database it is registered only once.

Is there a way to fix it so that at the time of making a record it is displayed only once in the file and saved in SQL at the same time?

try

{

Connection  conexion=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba","sa","sa");

                PreparedStatement statement =conexion.prepareStatement("Insert into datos values (?,?,?)");         
                statement.setString(1,texto1.getText());
                statement.setString(2,texto2.getText());
                statement.setInt(3, Integer.parseInt(texto3.getText()));
                statement.executeUpdate();
                //PreparedStatement statement1 =conexion.prepareStatement("Select *from datos");
                 Statement statement1 = conexion.createStatement();
                ResultSet rs=statement1.executeQuery("Select nombre,apellido,edad from datos");

                while(rs.next())
                {
                    Object dato[]=new Object[3];

                    for (int i=0;i<3;i++)
                     {
                          dato[i] = rs.getObject(i+1);  
                     }
                   modelo.addRow(dato);

                }
                rs.close();

                tabla1.updateUI();



            }
            catch(Exception e1)
            {

                e1.printStackTrace();
            }
    
asked by vegetto 19.12.2017 в 21:28
source

2 answers

1

Change your query for example: If the main key of the data table were auto-numeric, the query would go like this: "Select name, surname, age from data where idDato = (select MAX (dataData) from data)" And in instead of a while you should use an if. if (rs.next ()) {...}

The best option would be to assign it to an Int variable when executing data storage. This will save the number of rows inserted in the Int variable. It would be like this: int res = statement.executeUpdate (); And to insert the row of data res must be greater than 0. if (res > 0) {

    
answered by 20.12.2017 / 04:29
source
1

The problem is that you add rows to your JTable every time you register data, but they overlap the rows that you already have added, so there are repeated rows. You can delete all the rows of the JTable each time you insert data with the following code: model.setRowCount (0); And then add the rows product of the query. Another option would be to change the query so that it loads only the data you inserted and thus only inserts the row corresponding to the inserted data into the JTable.

    
answered by 20.12.2017 в 01:01