Just need to "refresh" the screen and show the new Data...

// Here's my code. I CAN insert data to my table, but I can't show the new data in the JTextField.... Why? Where did I go wrong?

public void insertRegister() {

String title = "Inserting new register...";

String sql = "INSERT INTO CLIENTS (id_client, nome_client, tel_client) VALUES(?,?,?)";

try {

// Setting up the PreparedStatement

PreparedStatement preparedStatement = connection.prepareStatement(sql);

String tempId = JOptionPane.showInputDialog(null, "Enter ID Client:", title, 3);

int id = Integer.parseInt(tempId);

String name = JOptionPane.showInputDialog(null, "Enter name Cliente", title, 3);

String tel = JOptionPane.showInputDialog(null, "Enter tel Client:", title, 3);

// Now we insert the real values for PreparedStatement and execute it!

preparedStatement.setInt(1, id);

preparedStatement.setString(2, name.toUpperCase());

preparedStatement.setString(3, tel);

preparedStatement.executeUpdate();

sql = "SELECT id_client, name_client, tel_client FROM CLIENTS";// Changing value of sql for a new query.

ResultSet resultSet = preparedStatement.executeQuery();

while(resultSet.next()) {

// obviously these variables were defined before in class...

clientId = resultSet.getInt("id_client");

clientNome = resultSet.getString("name_client");

clientTel = resultSet.getString("tel_client");

idText.setText(String.valueOf(clientId));

nameText.setText(clientName);

telText.setText(clientTel);

}

}

catch(SQLException s) { s.printStackTrace(); }

}

In my table the new values are inserted, but I cant show them in the JTextField. The last tuple is still on screen, but the new one should be showed. Why? Where did I go wrong?

Thanks!

[1842 byte] By [coffee95a] at [2007-10-2 21:54:16]
# 1

There are two problems in your code that I can see.

First, your sql query (SELECT id_client, name_client, tel_client FROM CLIENTS) will return all the rows in the table, not just one if in fact there are more than one rows in the clients table.

Second, You put idText.setText(String.valueOf(clientId)) , nameText.setText(clientName) and telText.setText(clientTel) in a while loop, so If the resultSet has more than one rows then your textfields will be reset that many times and only the last row will be shown on the fields which might not be the one you just inserted. That is why you don't see the text fields changed to what you inserted.

tdna at 2007-7-14 1:10:12 > top of Java-index,Java Essentials,New To Java...
# 2
Well, but how can I fix this?How?
coffee95a at 2007-7-14 1:10:12 > top of Java-index,Java Essentials,New To Java...
# 3
- Modify your sql query to specificly get your inserted row by using the WHERE clause. - Do not set the text fields inside a while loop.
tdna at 2007-7-14 1:10:12 > top of Java-index,Java Essentials,New To Java...