2012-03-08 6 views
0

編集:oops。これらのJDBCステートメントは機能します。私はSQL Plusでコミットするのを忘れていました。ありがとうポール。JDBC ResultSet集計関数

私は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

+1

私は最初の型(getInt(1)付き)を文字通り何百回もやったことがあり、常に動作します。プログラムとSQL * Plusで同じデータベースを使用しているようなことは、あなたが私たちに言っていないこととは違うことがありますか? –

答えて

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を使用する予定がある場合は、全体的に行き渡り、バインドされた変数を使用することもできます。 –

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`** 

私はここでループしながら、使用の必要性を全く考えていません。私が間違っているなら、私に知らせてください。