Java:使用Prepared Statements在MySQL数据库中插入批处理数据

时间:2014-11-14 12:13:57

标签: java mysql database prepared-statement batch-processing

我创建了一个自定义函数来在我的MySQL数据库中插入数据。这些函数首先根据给定的输入创建查询。查询看起来像INSERT INTO tableName (columnName1, ..., columnNamei) VALUES (?, ..., ?), ..., (?, ...,?)。之后,需要制作PreparedStatement,其中包含实际值。这些需要添加到批处理中,因为我想一次添加多行(如下所示:Java: Insert multiple rows into MySQL with PreparedStatement)。这是代码:

insertData()函数

public static void insertData(String table, List<HashMap<String, Object>> list) throws SQLException {

    //Create query: make sure all of the rows in the table get the same amount of values passed
    //Prepare colnames string
    String colNamesParsed = "";
    int counter = 1;

    //Iterate over only the first hashmap of the list (THATS WHY ALL THE ROWS NEED TO HAVE THE SAME AMOUNT OF VALUES PASSED)
    for (String colName : list.get(0).keySet()) {

        //Check if it is the last col name
        if (counter != list.get(0).keySet().size()) {
            colNamesParsed = colNamesParsed + colName+", ";
        }
        else {
            colNamesParsed = colNamesParsed + colName;
        }

        counter++;
    }

    //Now create the place holder for the query variables
    String queryVariablesPlaceholder = "";
    int rowSize = 0;
    for (HashMap<String, Object> row : list) {

        //This part is to check if all row sizes are equal
        if (rowSize == 0) {
            rowSize = row.values().size();
        }
        else {
            //Check if the rowsize is equal for all rows
            if (row.values().size() != rowSize) {
                System.out.println("The rows of the arrays are from a different size");
                return;
            }
        }

        String queryVariablesRow = "(?, ";
        for (int j = 1; j < (row.values().size()-1); j++) {
            queryVariablesRow = queryVariablesRow+"?, ";
        }
        queryVariablesRow = queryVariablesRow+"?)";

        //Make sure the query does not start with a comma
        if (queryVariablesPlaceholder.equals("")) {
            queryVariablesPlaceholder = queryVariablesRow;
        }
        else {
            queryVariablesPlaceholder = queryVariablesPlaceholder+", "+queryVariablesRow;
        }
    }

    //The MySQL query needs to be built now
    String query = "INSERT INTO "+table+" ("+colNamesParsed+") VALUES "+queryVariablesPlaceholder+";";
    System.out.println(query);

    //Init prepared statement
    PreparedStatement statement = con.prepareStatement(query);

    for (HashMap<String, Object> map : list) {

        int varCounter = 1;
        //Iterate over all values that need to be inserted
        for (Object object : map.values()) {

            if (object instanceof Integer) {
                statement.setInt(varCounter, Integer.parseInt(object.toString()));
            }
            else if (object instanceof String) {
                statement.setString(varCounter, object.toString());
            }
            else if (object instanceof Timestamp) {
                statement.setTimestamp(varCounter, parseStringToTimestamp(object.toString()));
            }
            else if (object instanceof Double) {
                statement.setDouble(varCounter, Double.parseDouble(object.toString()));
            }
            System.out.println(varCounter);
            varCounter++;
        }

        //Add row to the batch
        try {
            statement.addBatch();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

    }
    //Execute the query, which is in fact the batch
    statement.executeBatch();
}

当我想在数据库中插入一些数据时,我执行以下代码:

功能部分

List<HashMap<String, Object>> list = new ArrayList<>();
    for (Object object : listOfObjects) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("columnName1", object.getSomeValue());
        /....../
        map.put("columnName2", object.getSomeOtherValue());

        list.add(map);
    }

    Functions.insertData("tableName", list);

创建动态查询似乎完美无缺。但是,我无法让statement.addBatch()工作。它一直给我以下错误:

java.sql.SQLException: No value specified for parameter 9

我没有得到它,因为我只有8个参数传递给批处理的每个单元。我的目标表有9列,所以我尝试为该列添加一个值,但后面却说:No value specified for parameter 10,所以看起来它并没有关闭批量单位&#39;什么的。

我在这里缺少什么?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

INSERT INTO tableName (columnName1, ..., columnNamei) VALUES (?, ..., ?), ..., (?, ...,?) 

不是标准的SQL语法。 如果你使用这个JDBC将为每个&#34;?&#34;在您的查询中。

使用:

INSERT INTO tableName(columnName1,...,columnNamei)VALUES(?,...,?)

并将每个语句添加到批处理中。