数据库Java Bean SQL语句

时间:2014-12-30 19:18:23

标签: java jdbc

在我的数据库bean中,我有一段代码如下:

public Integer getTotalOrgPoints() {
        try {
            PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                totalOrgPoints = rs.getInt(1);
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return totalOrgPoints;
    }

对于语句QUERY_TOTAL_ORG_SCORE,如果我使用

SELECT SUM(users.score) 
FROM   user_organisation_relationships 
       INNER JOIN users 
               ON user_organisation_relationships.user_id = users.id 
WHERE  organisation_id = 1 

它将返回该组织的值,但如果我使用

SELECT SUM(users.score) 
FROM   user_organisation_relationships 
       INNER JOIN users 
               ON user_organisation_relationships.user_id = users.id 
WHERE  organisation_id = ? 

我什么都不知道为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

添加此行以在executequery

之前绑定预准备语句的值
stmt.setInt(1, 1);

修改: -

PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
stmt.setInt(1, 1);
ResultSet rs = stmt.executeQuery();