Java: Insert multiple rows into MySQL with PreparedStatement

后端 未结 6 1257
后悔当初
后悔当初 2020-11-22 16:28

I want to insert multiple rows into a MySQL table at once using Java. The number of rows is dynamic. In the past I was doing...

for (String element : array)          


        
6条回答
  •  一生所求
    2020-11-22 16:46

    If you can create your sql statement dynamically you can do following workaround:

    String myArray[][] = { { "1-1", "1-2" }, { "2-1", "2-2" }, { "3-1", "3-2" } };
    
    StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");
    
    for (int i = 0; i < myArray.length - 1; i++) {
        mySql.append(", (?, ?)");
    }
    
    myStatement = myConnection.prepareStatement(mySql.toString());
    
    for (int i = 0; i < myArray.length; i++) {
        myStatement.setString(i, myArray[i][1]);
        myStatement.setString(i, myArray[i][2]);
    }
    myStatement.executeUpdate();
    

提交回复
热议问题