现在,我遇到了这个问题:我想在GUI中显示我数据库中的歌曲总量(通过jtextfield)。
这是我到目前为止所得到的:
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);
答案 0 :(得分:1)
尝试
而不是while循环if(rs.first())
xtTotalSongs.setText(rs.getString("title"));
如果结果集中有一行,则rs.first()返回true(并将指针移动到第一个)。 getString返回列的值" title"在第一行。
因为" Count" (至少我猜是这样),这应该有用。
答案 1 :(得分:0)
while(rs.next()){
txtTotalSongs.setText(String.valueOf("title"));
// This doesn't get any value from rs
// It just get value "title".
}
更改你的while循环如下:
while(rs.next())
{
txtTotalSongs.setText(rs.getInt(1));
}
答案 2 :(得分:0)
我会在actionPerformed之外设置它。
txtTotalSongs = new JTextField();
txtTotalSongs.setBounds(591, 458, 86, 20);
contentPane.add(txtTotalSongs);
txtTotalSongs.setText(getTotalSongs());
然后在某处添加方法:
// 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;
}
}
如果你想定期更新计数,你可以运行一个计时器,更新时要小心threadsafety。