【问题标题】:How can I return an integer from a dao function?如何从 dao 函数返回整数?
【发布时间】:2012-07-19 07:24:51
【问题描述】:

在一个 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 作为(我猜)成功。但我希望它返回执行此查询的结果。

【问题讨论】:

  • 我猜除了 executeupdate 之外还有另一个功能可以满足我的需要。

标签: java jakarta-ee oracle10g dao


【解决方案1】:
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);
}

【讨论】:

  • 在这方面@Boris Pavlović 我想澄清一下何时使用更新以及何时使用查询?
猜你喜欢
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-23
  • 1970-01-01
相关资源
最近更新 更多