我将此String
sql
结果转换为int时遇到问题。你们能告诉我们如何做到这一点。
我这样做是因为我需要将此值设置为显示出勤次数的JLabel
。
我试图在这里寻找答案,但我找不到它。请你帮我解决这个问题吗?
public static int attendanceCount() throws ClassNotFoundException, SQLException {
String sql = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
Statement stm = conn.createStatement();
ResultSet rst = stm.executeQuery(sql);
return rst; // How do I convert this into integer?
}
这就是我需要完成的事情。
private void setAttendanceTile() {
try {
int attendanceCount = AttendanceController.attendanceCount();
inHouseMembersLabel.setText(Integer.toString(attendanceCount));
} catch (ClassNotFoundException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
或者,如果没有这样做,还有另一种方法可以实现吗?
感谢。
答案 0 :(得分:0)
您可以使用ResultSet.getInt()
方法。它需要column index或column name。 Here's an example from Oracle
在你的情况下你需要一个取索引的那个(注意索引从1开始,而不是0)。
答案 1 :(得分:0)
获取ResultSet.getInt(1):
int id = rst.getInt(1);
答案 2 :(得分:0)
如前所述,请尝试使用.getInt()
方法
而且,我会使用PreparedStatement
。使用PreparedStatement
非常重要,因为它允许数据库缓存您的查询
此外,使用后请务必关闭Connection
和ResultSet
。
public static int attendanceCount() throws ClassNotFoundException, SQLException {
final int COLUMN_NO = 1;
final String SQL = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
PreparedStatement stm = conn.prepareStatement(SQL);
ResultSet rst = stm.executeQuery();
int result = rst.getInt(COLUMN_NO);
try {
rst.close();
conn.close();
} catch (SQLException e) {} //ignore
return result;
}