2012-03-08 81 views
0

编辑:oops。这些JDBC语句有效;我忘记了在SQL Plus中提交。谢谢保罗。JDBC结果集合函数

当我查询与SQL Plus中的数据库:

select count(tid) from retweets where tid = 35   => 2 
select count(tid) from tweets where replyto = 35  => 1 

我试过几种方法来拉这些汇总计算从通过JDBC, 数据库,但在任何情况下,他们回到0

示例:

Statement stmt = m_con.createStatement(); 
ResultSet retweets = stmt.executeQuery("select count(tid) from retweets where tid = 35"); 

if (retweets.next()) { System.out.println("# of Retweets: " + retweets.getInt(1));} 
ResultSet replies = stmt.executeQuery("select count(tid) Replies from tweets where replyto = "+tid); 


if (replies.next()) {System.out.println("# of Replies : " + replies.getInt("Replies"));} 

两次都打印出0。为什么会发生这种情况,我该如何解决?谢谢。

+1

没有冒犯,但是你确定在转发或推文中有对应于35的记录吗? – gangreen 2012-03-08 01:44:00

+1

我已经完成了第一种类型(getInt(1))几乎数百次,并且它始终有效。必须有不同的东西,你不告诉我们,就像你使用相同的数据库的程序和SQL * Plus? – 2012-03-08 01:47:04

回答

2

事情是这样的:

public class TweetDao { 
    private static final String SELECT_TWEETS = "SELECT COUNT(tid) as TC FROM TWEETS WHERE replyTo = ? "; 
    // inject this - setter or constructor 
    private Connection connection; 

    public int getTweetCount(int tid) throws SQLException { 
     int tweetCount = -1; 
     PreparedStatement ps = null; 
     ResultSet rs = null; 
     try { 
      ps = this.connection.prepareStatement(SELECT_TWEETS); 
      ps.setInt(1, tid); 
      rs = ps.executeQuery(); 
      while (rs.hasNext()) { 
       tweetCount = rs.getInt("TC"); 
      } 
     } finally { 
      DatabaseUtils.close(rs); 
      DatabaseUtils.close(ps); 
     } 
     return tweetCount; 
    } 
} 
1

尝试PreparedStatement

String sql = "select count(tid) from retweets where tid = 35"; 
PreparedStatement stmt = m_con.prepareStatement(sql); 
+0

如果你打算使用PreparedStatement,那么你可能会走完整路并使用绑定变量。 – 2012-03-08 02:04:18

0
**try { 
      ps = this.connection.prepareStatement(SELECT_TWEETS); 
      ps.setInt(1, tid); 
      rs = ps.executeQuery(); 
      while (rs.hasNext()) { 
       tweetCount = rs.getInt("TC"); 
      } 
     } finally { 
      DatabaseUtils.close(rs);`enter code here`** 

我觉得这里没有必要使用while循环,因为我们只得到一个结果的。请让我知道,如果我错了。