如何提高许多数据库插入的性能?

时间:2015-09-18 11:57:57

标签: java mysql performance prepared-statement

我有以下代码在数据库上执行许多插入。有没有办法提高性能?怎么样?

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

由于

1 个答案:

答案 0 :(得分:1)

您应该使用 useServerPrepStmts = false rewriteBatchedStatements = true

Connection connection = DriverManager.getConnection("jdbc:mysql://<host Name>:<port name>/schema?useServerPrepStmts=false&rewriteBatchedStatements=true", "DB Username", "DB Password")

enter image description here