我怎样才能提高许多数据库插入的性能?
How can i improve performance of many database inserts?
我有以下代码在数据库上执行许多插入操作。有没有办法提高性能?怎么样?
public void insertMany(List<Trajectory> trajectories) {
try {
String sql = "insert into trajectory (id, datetime, longitude, latitude) values (?, ?, ?, ?)";
PreparedStatement insert = MySqlDriver.getInstance().getConnection().prepareStatement(sql);
try {
for (Trajectory trajectory : trajectories) {
insert.setLong(1, trajectory.getId());
insert.setTimestamp(2, Timestamp.valueOf(trajectory.getDateTime()));
insert.setDouble(3, trajectory.getLongitude());
insert.setDouble(4, trajectory.getLatitude());
insert.addBatch();
}
insert.executeBatch();
} finally {
insert.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
谢谢
您应该使用 useServerPrepStmts=false 和 rewriteBatchedStatements=true
Connection connection = DriverManager.getConnection("jdbc:mysql://<host Name>:<port name>/schema?useServerPrepStmts=false&rewriteBatchedStatements=true", "DB Username", "DB Password")
我有以下代码在数据库上执行许多插入操作。有没有办法提高性能?怎么样?
public void insertMany(List<Trajectory> trajectories) {
try {
String sql = "insert into trajectory (id, datetime, longitude, latitude) values (?, ?, ?, ?)";
PreparedStatement insert = MySqlDriver.getInstance().getConnection().prepareStatement(sql);
try {
for (Trajectory trajectory : trajectories) {
insert.setLong(1, trajectory.getId());
insert.setTimestamp(2, Timestamp.valueOf(trajectory.getDateTime()));
insert.setDouble(3, trajectory.getLongitude());
insert.setDouble(4, trajectory.getLatitude());
insert.addBatch();
}
insert.executeBatch();
} finally {
insert.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
谢谢
您应该使用 useServerPrepStmts=false 和 rewriteBatchedStatements=true
Connection connection = DriverManager.getConnection("jdbc:mysql://<host Name>:<port name>/schema?useServerPrepStmts=false&rewriteBatchedStatements=true", "DB Username", "DB Password")