I would like to obtain a messageDialog if the id which I'm filtering is not in the table model I created. The problem is that the code works fine without the if
, however when I add the if
for the messageDialog condition, I realize that the data is found but not shown.
Code:
public void buscarNumeroSerie (String nserie)
{
try {
String [] campos={"NUMERO_SERIE","MARCA","GAVETA"};
String filtroNS = nserie;
String NSSQL = "SELECT NUMERO_SERIE,MARCA,GAVETA FROM"
+ "(SELECT NUMERO_SERIE,MARCA,GAVETA FROM discos_wd "
+ "UNION "
+ "SELECT NUMERO_SERIE,MARCA,GAVETA FROM discos_toshiba "
+ "UNION "
+ "SELECT NUMERO_SERIE,MARCA,GAVETA FROM discos_seagate "
+ "UNION "
+ "SELECT NUMERO_SERIE,MARCA,GAVETA FROM discos_samsung "
+ "UNION "
+ "SELECT NUMERO_SERIE,MARCA,GAVETA FROM discos_hitachi )"
+ "AS TROUBLE WHERE NUMERO_SERIE LIKE '%"+filtroNS+"%'";
System.out.println(NSSQL);
nsconn = metodosPool.dataSource.getConnection();
ModeloTablaLista = new DefaultTableModel(null, campos);
stmnt = nsconn.prepareStatement(NSSQL);
ResultSet nsrs = stmnt.executeQuery(NSSQL);
if(nsrs.next()== true){
String [] nsfila = new String[3];
while (nsrs.next())
{
nsfila[0]=nsrs.getString("Numero_Serie");
nsfila[1]=nsrs.getString("Marca");
nsfila[2]=nsrs.getString("Gaveta");
ModeloTablaLista.addRow(nsfila);
}
nsrs.close();
stmnt.close();
tablaDiscosGaveta.setModel(ModeloTablaLista);
}
else
{
System.err.println("No existen datos asociados");
JOptionPane.showMessageDialog(rootPane, "Disco no encontrado, quiere:");
}
My idea is that the left image, that which contains the if
bit of code, shows the results I need just like the image on the right. I've tried with for
loops, adding a new resultSet and changing the position of the if
condition without results.
nsrs.next()
moves to the next record in the ResultSet
, so
if(nsrs.next()== true){
String [] nsfila = new String[3];
moves to the first record.
Then
while (nsrs.next()) {
moves to the second record, and the first record is skipped. So the code needs to process the record before moving to the next record. Here's a different approach:
//if(nsrs.next()== true){
// String [] nsfila = new String[3];
String [] nsfila = null;
while (nsrs.next()) {
nsfila = new String[3];
nsfila[0]=nsrs.getString("Numero_Serie");
nsfila[1]=nsrs.getString("Marca");
nsfila[2]=nsrs.getString("Gaveta");
ModeloTablaLista.addRow(nsfila);
}
if (nsfila == null) {
// no data...
}
See also: try with resources, or close()
in a finally block.