Skip to content
Advertisement

Java: Retrieve and display value from database in label

I am building a Java desktop app using Java Swing.

This is the select service method

public void select(int id){
        String sql = "SELECT num_of_working_days FROM working_days_and_hours WHERE id = ?";
        
         try {
            connection = SQLite_Connection.connect();
            preparedStatement = connection.prepareStatement(sql);
            
            preparedStatement.setInt(1, id);
            
            preparedStatement.execute();
            preparedStatement.close();

            System.out.println("DB status 1: "+ preparedStatement.toString());

        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }

I would like to display the result of this in a label

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        jLabel1.setText(numberOfDays.select(1));     
        // numberOfDays.select(1);
        System.out.println("Entered: " + jTextField1.getText());
       
    } 

There is an error at jLabel1.setText(numberOfDays.select(1)); Saying ‘void type not allowed here’.

What am I doing wrong? Appreciate any input regarding this matter. Thank you.

Advertisement

Answer

your select method definition

public void select(int id)

This returns void

Looking at the Java doc JLabel: setText(String str) This method requires a string DataType

Hence change ur method select to return a String i.e.

public String select(int id)

also in ur method Store the result from prepared statement like below

    ResultSet rs = preparedStatement.executeQuery();        // Get the result table from the q
    while (rs.next()) {               // Position the cursor to the result 
      String result = rs.getInt(1); //If ur Column is of int type
    }
preparedStatement.close();
return result;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement