JDBC:まとめてInsert(multi-row insert) | 熱脳しゃちょのブログ

熱脳しゃちょのブログ

おせっかい焼SE兼プログラマ兼……の辛い日々と、思う事なぞ

MySqlの
INSERT INTO ××× VALUES(...,...,...,).(...,...,...,).(...,...,...,).(...,...,...,)
をJDBCでやろうじゃないか、という話。

コネクションを張るときに、RewriteBatchedStatementsをTrueに。
connection.setRewriteBatchedStatements(true);
使うPreparedStatementはサーバサイドは使っちゃダメ(JDBC内で書き換るから)。つまり、
connection.serverPrepareStatement(...);
は×。
mysql_server_prepare=1
とかも、×。
で、
prep.executeUpdate();
のかわりに
prep.addBatch();
を使い、最後に
int[] results = prep.executeBatch();
とやると、resultsにexecuteUpdate();で入るはずのaffected-row countが順に入る、と。

String prepSql = "INSERT INTO ...........VALUES(?,?,?)";
Connection connection = (Connection) DriverManager.getConnection(Url);
connection.setRewriteBatchedStatements(true);
PreparedStatement prep=connection.prepareStatement(prepSql);
for(Class c : classArray){
prep.setLong(1, c.Id);
prep.setString(2, c.Name);
...
prep.addBatch();
}
int[] results = prep.executeBatch();

こんな感じかな?
ローカルDBだと大した効果は期待できません。
もちろん、SELECTとかは、サーバサイドで使い回せば、早くなりますけど。