Skip to content

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);

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

        } catch (Exception ex) {

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:
        System.out.println("Entered: " + jTextField1.getText());

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

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


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 ( {               // Position the cursor to the result 
      String result = rs.getInt(1); //If ur Column is of int type
return result;