2012-03-08 108 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循環,因爲我們只得到一個結果的。請讓我知道,如果我錯了。