如何从dao函数返回一个整数?

时间:2012-07-19 07:24:52

标签: java java-ee oracle10g dao

在servlet程序中,我创建了一个包含函数的DAO类,我希望返回一个通过执行Oracle查询生成的特定值。我尝试过这样的事情:

public int timeofdayafternoonthsmon(Getset g) throws ClassNotFoundException, SQLException {
    // TODO Auto-generated method stub
    Connection con=Dbconnection.getConnection();
    String userid=g.getuserid();
    PreparedStatement pstmt=con.prepareStatement("select count(timeofday) from mealdb where timeofday=? and userid=?");
    pstmt.setString(1,"Afternoon");
    pstmt.setString(2,userid);
    int no=pstmt.executeUpdate();
    System.out.println(""+no);
    return no;
}

但问题是它回归1(我猜)成功。但我希望它返回执行此查询的结果。

1 个答案:

答案 0 :(得分:2)

public int timeofdayafternoonthsmon(Getset g) throws ClassNotFoundException, SQLException {
    // TODO Auto-generated method stub
    Connection con=Dbconnection.getConnection();
    String userid=g.getuserid();
    PreparedStatement pstmt=con.prepareStatement("select count(timeofday) from mealdb where timeofday=? and userid=?");
    pstmt.setString(1,"Afternoon");
    pstmt.setString(2,userid);

    // execute a query, not an update statement and fetch the result set
    ResultSet rs = stmt.executeQuery();
    // position to the first result, there must be one since count(timeofday) returns at least 0
    rs.next();

    System.out.println(""+rs.getInt(1));
    return rs.getInt(1);
}