如何在Map数据上建立sql基础

时间:2013-04-21 05:41:41

标签: java sql

我的下面的方法接受两个参数 -

userId and attributes Map

属性Map将具有列名和列值 -

让我们举一个例子,如果我在上面的地图中有5列,那么将会有5个键和5个值。

所以我的SQL看起来像这样 -

String sql = "INSERT INTO PROFILE(userId, colA, colB, colC, colD, colE) VALUES ( ?, ?, ?, ?, ?, ?) ";

以同样的方式,我的查询语句看起来像 -

BoundStatement query = prBatchInsert.bind(userId, colAValue, colBValue, colCValue, colDValue, colEValue);

但在某些情况下,属性映射可能有20列。基于此,我需要制作sql和query语句。

下面的代码几乎假设该表只有四列不对。

public void upsertAttributes(final String userId, final Map<String, String> attributes) {

    try {
        String[] keys = (String[])attributes.keySet().toArray();

        String sql = "INSERT INTO PROFILE(userId, "+keys[0]+", "+keys[1]+", "+keys[2]+", "+keys[3]+") VALUES ( ?, ?, ?, ?, ?) "; 

        BoundStatement query = prBatchInsert.bind(userId, attributes.get(keys[0]), attributes.get(keys[1]), attributes.get(keys[2]), attributes.get(keys[3]));

    } catch (Exception e) {
        LOG.error(e);
    }

}

如何编写与attributes Map相对应的更通用的方法?

1 个答案:

答案 0 :(得分:0)

你应该使用Spring jdbctemplate,它有很多api。查看此链接:http://static.springsource.org/spring/docs/2.0.8/api/org/springframework/jdbc/core/JdbcTemplate.html

编辑:

点击此链接:http://www.mkyong.com/spring/spring-named-parameters-examples-in-simplejdbctemplate/

它完全符合您的要求。

编辑:如果您不想使用Spring,那么为了实现这一点,您需要动态生成完整的sql字符串。不会使用绑定。

请参阅此代码[我没有运行此代码,但这是实现此目的的基本思路]:

public void upsertAttributes(final String userId, final Map<String, String> attributes) {

    try {
        String[] keys = (String[])attributes.keySet().toArray();

        String sql = "INSERT INTO PROFILE(userId, "+keys[0]+", "+keys[1]+", "+keys[2]+", "+keys[3]+") VALUES ( ?, ?, ?, ?, ?) "; 
        StringBuffer keysStmt = new StringBuffer("INSERT INTO PROFILE("+userId);
        StringBuffer valuesStmt = new StringBuffer("  VALUES (" );

        Iterator itr = attributes.keySet().iterator();

        while(itr.hasNext()){
            String key = itr.next();
            keysStmt.append(","+key);
            valuesStmt.append(attributes.get(key)+",");          
        }

       //remove last comma
       valuesStmt = new StringBuffer(valuesStmt.toString().substring(0,valuesStmt.length-1));

       sql = keysStmt.append(")")+valuesStmt.append(")");

    } catch (Exception e) {
        LOG.error(e);
    }

}