0
public ResultSet getAdCampaignDetailsbyName(ADCampaignDetails Obj,
            Connection conn, ResultSet rs, PreparedStatement pstmt) throws SQLException {

        String query = "select adCampaignName,adCampaignId from AdCampaignDetails";
        query += " where 1=1 ";

        if (Obj.getAdCamapignName() != null)
            query += " and adCampaignName = ?";
        if (Obj.userId != "")
            query += " and userId = ?";

        pstmt = conn.prepareStatement(query);

        int i = 0;

        if (Obj.getAdCamapignName() != null)
            pstmt.setString(++i, Obj.getAdCamapignName());
        if (Obj.userId != "")
            pstmt.setString(++i, Obj.userId);

        System.out.println(" Q : " + query);

        rs = pstmt.executeQuery();


        return rs;
    }

我是 Spring 新手,在上面的查询中,我使用了两个条件,如何在 Spring JDBC 框架中使用条件执行查询?

4

1 回答 1

3

您可以使用SimpleJDBCTemplate

    // SQL query
    String query = "select adCampaignName,adCampaignId from AdCampaignDetails where 1=1";

    // Map with parameter value
    Map<String, Object> parameters = new HashMap<String, Object>();
    if (adCampaignName!=null){
        parameters.put("adCampaignName ", adCampaignName );
        query += " AND adCampaignName = :adCampaignName"; 
    }
    if (userId!=null){
        parameters.put("userId", 1);
        query += " AND userId= :userId"; 
    }

    // Execute query using simpleJDBC Template
    List<AdCampaignDetails> resultList = getSimpleJdbcTemplate().query(query, new customRowMapper(), parameters);   

您可以相应地构建查询字符串,只需在地图中添加相应的条目。
检查此链接以获取详细信息。

于 2012-07-19T11:49:34.700 回答