Java 将 HashMap 插入任何数据库表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20150880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:31:19  来源:igfitidea点击:

Insert a HashMap into any database table

javajdbc

提问by RazorHead

I have a HashMap with the following definition:

我有一个具有以下定义的 HashMap:

  myMap = new HashMap<String,String>();

this map consists of the field names as keys and field values as of course values. I am trying to make a method that takes the HashMap and a table name as arguments. My query has to have the following format because I do not insert to all the columns in my table:

该映射由作为键的字段名称和作为课程值的字段值组成。我正在尝试创建一个将 HashMap 和表名作为参数的方法。我的查询必须具有以下格式,因为我没有插入表中的所有列:

INSERT INTO $tableName (?,?,?,?)
VALUES (?,?,?,?)

The number of columns of course depends on the size of the HashMap. How can I achieve this through iterating through the HashMap. Here is what I have come up so far using a different approach but I do not think it will work properly:

列数当然取决于 HashMap 的大小。我如何通过遍历 HashMap 来实现这一点。这是我到目前为止使用不同的方法提出的问题,但我认为它不会正常工作:

public void insertData(HashMap<String, String> dataMap, String tableName) {

    int size=dataMap.size();
    String sql = "INSERT INTO " + tableName;
    Iterator<Entry<String, String>> it = dataMap.entrySet().iterator();
    int counter = 1;
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        sql += pairs.getKey()+"="+pairs.getValue();
        if(size > counter )
            sql += ", ";
        counter++;
    }
    sql += ";";
}

采纳答案by BalusC

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

您需要自己生成带有列名和占位符的准备好的语句 SQL 字符串。这是一个启动示例:

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 Objectcan also be a Number(Integer, Long, etc), Date, byte[], and so on, at least those types for which the PreparedStatementalready has setter methods.

这具有额外的优势,您可以使用Map<String, Object>whereObject也可以是Number( IntegerLong等)、Datebyte[]等,至少是那些PreparedStatement已经具有 setter 方法的类型。

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

请记住,如果tableName和 映射键由最终用户控制,则您将面临严重的 SQL 注入攻击漏洞。