Izzie Ruslim
Izzie Ruslim

Reputation: 1

How to show "count" MySQL query into JTextField?

Right now, I'm stuck with this problem: I want to show the total amount of songs in my database inside the GUI (through the jtextfield).

This is what I got so far:

txtTotalSongs = new JTextField();
txtTotalSongs.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        try {
            String q = "select count (title) from songs";
            PreparedStatement ps=conn.prepareStatement(q);

            ps.setInt(1, 20);

            ResultSet rs = ps.executeQuery();

            while(rs.next())
            {
                txtTotalSongs.setText(String.valueOf("title"));
            }

        } catch (Exception e) {
            // TODO: handle exception
        }

    }
});
txtTotalSongs.setBounds(591, 458, 86, 20);
contentPane.add(txtTotalSongs);

Upvotes: 0

Views: 2350

Answers (3)

Joeblade
Joeblade

Reputation: 1743

I would set this outside of the actionPerformed.

txtTotalSongs = new JTextField();
txtTotalSongs.setBounds(591, 458, 86, 20);
contentPane.add(txtTotalSongs);

txtTotalSongs.setText(getTotalSongs());

and then add a method somewhere:

// not ideal but trying to use most of your original code.
public int getTotalSongs() {
    try {
        String q = "select count (title) from songs";
        PreparedStatement ps=conn.prepareStatement(q);

        ps.setInt(1, 20);

        ResultSet rs = ps.executeQuery();

        if (rs.next()) {
            return rs.getInt(1);
        } else { 
            return 0;
        }
    } catch (Exception e) {
        // TODO: handle exception
        return 0;
    }
}           

if you want to regularly update the count, you can run a Timer, just be careful about threadsafety when updating.

Upvotes: 0

Salih Erikci
Salih Erikci

Reputation: 5087

while(rs.next()){
    txtTotalSongs.setText(String.valueOf("title"));
    // This doesn't get any value from rs
    // It just get value "title".
}

Change your while loop as below:

while(rs.next())
{
    txtTotalSongs.setText(rs.getInt(1));
}

Upvotes: 0

Phiwa
Phiwa

Reputation: 319

Instead of the while loop, try

if(rs.first())
    xtTotalSongs.setText(rs.getString("title"));

rs.first() returns true (and moves the pointer to the first) if there is a row in the result set. getString returns the value of the column "title" in the first row.

Since there should only be one row for "Count" (at least I guess so), this should work.

Upvotes: 1

Related Questions