编辑:oops。这些JDBC语句有效;我忘记了在SQL Plus中提交。谢谢保罗。
当我使用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。为什么会发生这种情况,我该如何解决?感谢。
答案 0 :(得分: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 :(得分:1)
尝试PreparedStatement
:
String sql = "select count(tid) from retweets where tid = 35";
PreparedStatement stmt = m_con.prepareStatement(sql);
答案 2 :(得分: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循环,因为我们只得到单个结果。如果我错了,请告诉我。