92

Javaを使用してMySQLテーブルに一度に複数の行を挿入したい。行数は動的です。過去に私がやっていたのは...

for (String element : array) {
    myStatement.setString(1, element[0]);
    myStatement.setString(2, element[1]);

    myStatement.executeUpdate();
}

MySQLでサポートされている構文を使用するようにこれを最適化したいと思います。

INSERT INTO table (col1, col2) VALUES ('val1', 'val2'), ('val1', 'val2')[, ...]

しかし、PreparedStatement要素がいくつ含まれるかを事前に知らないので、これを行う方法がわかりませんarray。でそれが不可能な場合PreparedStatement、他にどのようにそれを行うことができますか(それでも配列の値をエスケープできます)?

4

7 に答える 7

184

によってバッチを作成し、によってPreparedStatement#addBatch()実行することができますPreparedStatement#executeBatch()

キックオフの例は次のとおりです。

public void save(List<Entity> entities) throws SQLException {
    try (
        Connection connection = database.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
    ) {
        int i = 0;

        for (Entity entity : entities) {
            statement.setString(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
            i++;

            if (i % 1000 == 0 || i == entities.size()) {
                statement.executeBatch(); // Execute every 1000 items.
            }
        }
    }
}

一部のJDBCドライバやDBにはバッチ長に制限がある場合があるため、1000アイテムごとに実行されます。

も参照してください

于 2010-12-04T18:30:44.660 に答える
33

MySQLドライバーを使用する場合は、接続パラメーターrewriteBatchedStatementsをtrueに設定する必要があります( jdbc:mysql://localhost:3306/TestDB?**rewriteBatchedStatements=true**)

このパラメータを使用すると、テーブルが1回だけロックされ、インデックスが1回だけ更新されるときに、ステートメントが一括挿入に書き換えられます。したがって、はるかに高速です。

このパラメータがない場合の唯一の利点は、よりクリーンなソースコードです。

于 2014-05-29T16:22:35.577 に答える
8

SQLステートメントを動的に作成できる場合は、次の回避策を実行できます。

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();
于 2010-12-04T18:52:37.067 に答える
3

テーブルに自動インクリメントがあり、それにアクセスする必要がある場合は、次のアプローチを使用できます...使用するドライバーに依存するため、ステートメントのgetGeneratedKeys()を使用する前に、テストを実行してください。以下のコードは、MariaDB10.0.12およびMariaJDBCドライバー1.2でテストされています。

バッチサイズを大きくすると、パフォーマンスがある程度向上することを忘れないでください...私のセットアップでは、バッチサイズを500を超えると、実際にはパフォーマンスが低下していました。

public Connection getConnection(boolean autoCommit) throws SQLException {
    Connection conn = dataSource.getConnection();
    conn.setAutoCommit(autoCommit);
    return conn;
}

private void testBatchInsert(int count, int maxBatchSize) {
    String querySql = "insert into batch_test(keyword) values(?)";
    try {
        Connection connection = getConnection(false);
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean success = true;
        int[] executeResult = null;
        try {
            pstmt = connection.prepareStatement(querySql, Statement.RETURN_GENERATED_KEYS);
            for (int i = 0; i < count; i++) {
                pstmt.setString(1, UUID.randomUUID().toString());
                pstmt.addBatch();
                if ((i + 1) % maxBatchSize == 0 || (i + 1) == count) {
                    executeResult = pstmt.executeBatch();
                }
            }
            ResultSet ids = pstmt.getGeneratedKeys();
            for (int i = 0; i < executeResult.length; i++) {
                ids.next();
                if (executeResult[i] == 1) {
                    System.out.println("Execute Result: " + i + ", Update Count: " + executeResult[i] + ", id: "
                            + ids.getLong(1));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (connection != null) {
                if (success) {
                    connection.commit();
                } else {
                    connection.rollback();
                }
                connection.close();
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
于 2015-07-30T07:29:41.790 に答える
3

@AliShakibaコードを変更する必要があります。エラー部分:

for (int i = 0; i < myArray.length; i++) {
     myStatement.setString(i, myArray[i][1]);
     myStatement.setString(i, myArray[i][2]);
}

更新されたコード:

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(", (?, ?)");
}

mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());

for (int i = 0; i < myArray.length; i++) {
    myStatement.setString((2 * i) + 1, myArray[i][1]);
    myStatement.setString((2 * i) + 2, myArray[i][2]);
}

myStatement.executeUpdate();
于 2017-10-18T14:54:42.260 に答える
0

で複数の更新を送信することができますJDBC

自動コミットを無効にして、バッチ更新に、、、およびオブジェクトをStatement使用PreparedStatementできます。CallableStatement

addBatch()およびexecuteBatch()関数は、BatchUpdateを持つすべてのステートメントオブジェクトで使用できます。

ここでaddBatch()、メソッドは一連のステートメントまたはパラメーターを現在のバッチに追加します。

于 2013-08-15T14:18:40.340 に答える
0

これは、配列をに渡す場合に役立つことがありますPreparedStatement

必要な値を配列に格納し、それを関数に渡して同じものを挿入します。

String sql= "INSERT INTO table (col1,col2)  VALUES (?,?)";
String array[][] = new String [10][2];
for(int i=0;i<array.size();i++){
     //Assigning the values in individual rows.
     array[i][0] = "sampleData1";   
     array[i][1] = "sampleData2";
}
try{
     DBConnectionPrepared dbcp = new DBConnectionPrepared();            
     if(dbcp.putBatchData(sqlSaveAlias,array)==1){
        System.out.println("Success"); 
     }else{
        System.out.println("Failed");
     }
}catch(Exception e){
     e.printStackTrace();
}

putBatchData(sql、2D_Array)

public int[] putBatchData(String sql,String args[][]){
        int status[];
        try {
            PreparedStatement stmt=con.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                for(int j=0;j<args[i].length;j++){
                    stmt.setString(j+1, args[i][j]);
                }            
                stmt.addBatch();
                stmt.executeBatch();
                stmt.clearParameters();
            }
            status= stmt.executeBatch();             
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return status;
    }
于 2021-11-18T15:31:12.113 に答える