[英]JDBC ResultSet Aggregate Functions
Edit: oops. 编辑:哎呀。 These JDBC statements work;
这些JDBC语句有效。 I had forgotten to commit in SQL Plus.
我忘了提交SQL Plus。 Thanks Paul.
谢谢保罗。
When I query the database with SQL Plus: 当我使用SQL Plus查询数据库时:
select count(tid) from retweets where tid = 35 => 2
select count(tid) from tweets where replyto = 35 => 1
I've tried several methods to pull these aggregate counts from the database through JDBC, but in all cases they returned 0. 我尝试了几种方法通过JDBC从数据库中提取这些聚合计数,但是在所有情况下它们都返回0。
Examples: 例子:
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"));}
Both times, 0 was printed. 两次都打印0。 Why did this happen and how can I fix it?
为什么会发生这种情况,我该如何解决? Thanks.
谢谢。
Something like this: 像这样:
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;
}
}
Try PreparedStatement
: 尝试
PreparedStatement
:
String sql = "select count(tid) from retweets where tid = 35";
PreparedStatement stmt = m_con.prepareStatement(sql);
**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`**
I think here no need of using while loop because we are getting only single result. 我认为这里不需要使用while循环,因为我们只会得到单个结果。 Please let me know, if I am wrong.
如果我错了,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.