Insert a HashMap into any database table

后端 未结 1 1556
日久生厌
日久生厌 2021-01-07 13:32

I have a HashMap with the following definition:

  myMap = new HashMap();

this map consists of the field names as keys

相关标签:
1条回答
  • 2021-01-07 13:45

    You'd need to generate the prepared statement SQL string with column names and placeholders yourself. Here's a kickoff example:

    StringBuilder sql = new StringBuilder("INSERT INTO ").append(tableName).append(" (");
    StringBuilder placeholders = new StringBuilder();
    
    for (Iterator<String> iter = dataMap.keySet().iterator(); iter.hasNext();) {
        sql.append(iter.next());
        placeholders.append("?");
    
        if (iter.hasNext()) {
            sql.append(",");
            placeholders.append(",");
        }
    }
    
    sql.append(") VALUES (").append(placeholders).append(")");
    preparedStatement = connection.prepareStatement(sql.toString());
    int i = 0;
    
    for (String value : dataMap.values()) {
        preparedStatement.setObject(i++, value);
    }
    
    int affectedRows = prepatedStatement.executeUpdate();
    // ...
    

    This has the additional advantage that you can use Map<String, Object> where Object can also be a Number (Integer, Long, etc), Date, byte[], and so on, at least those types for which the PreparedStatement already has setter methods.

    Keep in mind that you've a serious SQL injection attack hole if the tableName and map keys are controlled by the enduser.

    0 讨论(0)
提交回复
热议问题