# Really slow MySQL inserts

**URL:** <https://users.rust-lang.org/t/really-slow-mysql-inserts/139200>\
**Category:** help\
**Created:** [March 27, 2026, 3:19am UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200 "2026-03-27T03:19:46Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![John\_Nagle](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/john_nagle/32/17844_2.png) [@John\_Nagle](https://users.rust-lang.org/u/John_Nagle)\
**Post date:** [March 27, 2026, 3:19am UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/1 "2026-03-27T03:19:46Z")

</div>

```rust
fn build_temporary_table(&self, tx: &mut Transaction) -> Result<(), Error> {
        const CREATE_INUSE_UUIDS_SQL: &str = r"CREATE TEMPORARY TABLE uuids_in_use (
            region_loc_x INT NOT NULL,
            region_loc_y INT NOT NULL,
            region_size_x INT NOT NULL,
            region_size_y INT NOT NULL,
            asset_type VARCHAR(20) NOT NULL,
            asset_uuid CHAR(36) DEFAULT NULL,
            asset_hash CHAR(8) NOT NULL)";
        const INSERT_INUSE_UUIDS_SQL: &str = r"INSERT INTO uuids_in_use
            (region_loc_x, region_loc_y, region_size_x, region_size_y, asset_type, asset_uuid, asset_hash)
            VALUES
            (:region_loc_x, :region_loc_y, :region_size_x, :region_size_y, :asset_type, :asset_uuid, :asset_hash)";
        // Get all the active UUIDs. In memory all at once, but under 1MB
        let active_uuids = self.get_uuids_in_use(tx)?;
        log::info!("{} active UUIDs: {:?}", active_uuids.len(), &active_uuids[0..5.min(active_uuids.len())]);
         // Create the temporary table
        tx.query_drop(CREATE_INUSE_UUIDS_SQL)?;
        log::info!("Temporary table created.");
        // Put all the records in the temporary table.
        tx.exec_batch(
            INSERT_INUSE_UUIDS_SQL,
            active_uuids.iter().map(|p| params! {
                "region_loc_x" => p.region_loc[0],
                "region_loc_y" => p.region_loc[1],
                "region_size_x" => p.region_size[0],
                "region_size_y" => p.region_size[1],
                "asset_uuid" => p.asset_uuid.to_string(),
                "asset_hash" => p.asset_hash.clone(),
                "asset_type" => p.asset_type.to_str().to_string(),
            })
        )?;
        log::info!("Temporary table filled.");
        Ok(())
    }

```

```rust
03:09:00 [INFO] 406 active UUIDs: ...
03:09:00 [INFO] Temporary table created.
03:09:26 [INFO] Temporary table filled.

```

For some reason, MySQL called from Rust took 26 seconds to insert 406 records into an empty temporary table. SELECT is fast, but INSERT is insanely slow. 15 records per second.

I tried ENGINE MEMORY (the data doesn't even go out to disk) and got

```rust
03:15:19 [INFO] Temporary table created.
03:15:45 [INFO] Temporary table filled.

```

so it still took 26 seconds. Same as with the default InnoDB engine. This suggests it's not the database engine that's the problem.

This is Dreamhost shared hosting, being tested using remote access to the MySQL database from the "mysql" crate.

Is there something really slow about how Rust does this? Extreme throttling of external INSERT operations on Dreamhost? Something else?

---

<div class="post-metadata">

**Author:** ![John\_Nagle](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/john_nagle/32/17844_2.png) [@John\_Nagle](https://users.rust-lang.org/u/John_Nagle)\
**Post date:** [March 27, 2026, 6:41am UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/2 "2026-03-27T06:41:02Z")

</div>

MySQL 8.0.0, which is old.

---

<div class="post-metadata">

**Author:** ![giocri](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/giocri/32/49821_2.png) [@giocri](https://users.rust-lang.org/u/giocri)\
**Post date:** [March 27, 2026, 9:12am UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/3 "2026-03-27T09:12:18Z")

</div>

i recommend you try accessing the database with some already existing frontend and see if the issue persists

---

<div class="post-metadata">

**Author:** ![hi\_sam](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/hi_sam/32/50978_2.png) [@hi\_sam](https://users.rust-lang.org/u/hi_sam)\
**Post date:** [March 27, 2026, 11:32am UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/4 "2026-03-27T11:32:44Z")

</div>

> [@John\_Nagle](#):
>
> ```rust
> asset_uuid CHAR(36) DEFAULT NULL,
> asset_hash CHAR(8) NOT NULL)";
> const INSERT_INUSE_UUIDS_SQL: &str = r"INSERT INTO uuids_in_use
> (region_loc_x, region_loc_y, region_size_x, region_size_y, asset_type, asset_uuid, asset_hash)
> VALUES
> (:region_loc_x, :region_loc_y, :region_size_x, :region_size_y, :asset_type, :asset_uuid, :asset_hash)";
> // Get all the active UUIDs. In memory all at once, but under 1MB
> let active_uuids = self.get_uuids_in_use(tx)?;
> log::info!("{} active UUIDs: {:?}", active_uuids.len(), &active_uuids[0..5.min(active_uuids.len())]);
> // Create the temporary table
> tx.query_drop(CREATE_INUSE_UUIDS_SQL)?;
> log::info!("Temporary table created.");
> // Put all the records in the temporary table.
> tx.exec_batch(
> INSERT_INUSE_UUIDS_SQL,
> active_uuids.iter().map(|p| params! {
> "region_loc_x" => p.region_loc[0],
> "region_loc_y" => p.region_loc[1],
> "region_size_x" => p.region_size[0],
> "region_size_y" => p.region_size[1],
> "asset_uuid" => p.asset_uuid.to_string(),
> "asset_hash" => p.asset_hash.clone(),
> "asset_type" => p.asset_type.to_str().to_string(),
> })
> )?;
> log::info!("Temporary table filled.");
> Ok(())
> }
> 
> ```
> 
> ```rust
> 03:09:00 [INFO] 406 active UUIDs: ...
> 03:09:00 [INFO] Temporary table created.
> 03:09:26 [INFO] Temporary table filled.
> 
> ```
> 
> For some reason, MySQL called from Rust took 26 seconds to insert 406 records into an empty temporary table. SELECT is fast, but INSERT is insanely slow. 15 records per second.
> 
> I tried ENGINE MEMORY (the data doesn't even go out to disk) and got
> 
> ```rust
> 03:15:19 [INFO] Temporary table created.
> 03:15:45 [INFO] Temporary table filled.
> 
> ```
> 
> so it still took 26 seconds. Same as with the default InnoDB engine. This suggests it's not the database engine that's the problem.
> 
> This is Dreamhost shared hosting, being tested using remote access to the MySQL database from the "mysql" crate.
> 
> Is there something really slow about how Rust does this? Extreme throttling of external INSERT operations on Dreamhost? Something else?

You're pasting row-by-row, then returning back (trip) so if you paste around 400 records it is going to send request 400times (50ms \* 400 = +-20sec). Problem is your implementation. Use multi-row insert, which will insert basically all of 400records at once.

```rust
INSERT INTO table (...) VALUES
(...),
(...),
(...),
...

```

-basically sending just a table

---

<div class="post-metadata">

**Author:** ![jdahlstrom](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/jdahlstrom/32/38017_2.png) [@jdahlstrom](https://users.rust-lang.org/u/jdahlstrom)\
**Post date:** [March 27, 2026, 11:52am UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/5 "2026-03-27T11:52:08Z")

</div>

One would naively assume that a function called `exec_batch` would actually send the statements as a batch, and not one statement per request (!!) but who knows…

---

<div class="post-metadata">

**Author:** ![John\_Nagle](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/john_nagle/32/17844_2.png) [@John\_Nagle](https://users.rust-lang.org/u/John_Nagle)\
**Post date:** [March 27, 2026, 6:01pm UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/6 "2026-03-27T18:01:03Z")

</div>

One would expect **exec\_batch** to do that efficiently. exec\_batch accepts an iterator for the data, so the whole point is to feed the database.

One giant VALUES clause would work for this test set, but the real data will have about 20,000 rows, which is too much for that approach.

I put a debug log entry inside the iterator to watch the insertions. 17 records in one second. Bleah. And that's with ENGINE MEMORY; no disk at all. And the table has no indices. See below.

I'm using the approach recommended in the "mysql" crate documentation here: [mysql - Rust](https://docs.rs/mysql/latest/mysql/) which is one SQL statement with an iterator providing the data. Reasonable.

I looked at the code in the "mysql" crate, at [rust-mysql-simple/src/conn/query.rs at 08b7f90aec8586e1fc64a3a1fa9cb09bfdce98aa · blackbeam/rust-mysql-simple · GitHub](https://github.com/blackbeam/rust-mysql-simple/blob/08b7f90aec8586e1fc64a3a1fa9cb09bfdce98aa/src/conn/query.rs#L343-L363)

Although the comments indicate it uses MySQL's bulk mode, what the code seems to do (look at the loop that begins at line 384) is iterate over "params" and do each substatement as a separate operation. Am I reading that right?

This is all so mainstream CRUD app it ought to Just Work. Missing something dumb here.

(Can't use LOAD DATA LOCAL; I'm not running on the same machine as the MySQL server.)

```rust
17:23:33 [INFO] Temporary table created.
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [262144, 262144]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [262144, 262144]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [278528, 262144]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [278528, 262144]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [278528, 278528]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [278528, 278528]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 262144]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 262144]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 266240]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 266240]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 270336]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 270336]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 274432]
17:23:33 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 274432]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 278528]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 278528]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 278528]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [286720, 278528]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [288768, 268288]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [288768, 268288]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [288768, 268288]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [288768, 268288]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [288768, 269312]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [288768, 269312]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [288768, 276480]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [288768, 276480]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [288768, 278528]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [288768, 278528]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [289280, 268288]
17:23:34 [DEBUG] (2) common::tileassetsgc: Inserting [289280, 268288]
17:23:35 [DEBUG] (2) common::tileassetsgc: Inserting [289280, 268800]
17:23:35 [DEBUG] (2) common::tileassetsgc: Inserting [289280, 268800]
17:23:35 [DEBUG] (2) common::tileassetsgc: Inserting [289280, 269312]

```

---

<div class="post-metadata">

**Author:** ![jumpnbrownweasel](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/jumpnbrownweasel/32/17403_2.png) [@jumpnbrownweasel](https://users.rust-lang.org/u/jumpnbrownweasel)\
**Post date:** [March 27, 2026, 6:04pm UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/7 "2026-03-27T18:04:51Z")

</div>

I want to second this recommendation:

> [@giocri](#):
>
> i recommend you try accessing the database with some already existing frontend and see if the issue persists

It seems very possible that the cloud service you're using is slow. You should at least rule that out.

---

<div class="post-metadata">

**Author:** ![jdahlstrom](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/jdahlstrom/32/38017_2.png) [@jdahlstrom](https://users.rust-lang.org/u/jdahlstrom)\
**Post date:** [March 27, 2026, 6:12pm UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/8 "2026-03-27T18:12:13Z")

</div>

Wrt efficient bulk insert, at least Postgres supports COPY FROM for loading serialized data fast, maybe Mysql has similar?

---

<div class="post-metadata">

**Author:** ![John\_Nagle](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/john_nagle/32/17844_2.png) [@John\_Nagle](https://users.rust-lang.org/u/John_Nagle)\
**Post date:** [March 27, 2026, 6:13pm UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/9 "2026-03-27T18:13:49Z")

</div>

It's a slow shared server, but 17TPS? Come on.

I think the Rust crate is doing a separate INSERT for each row, as I mentioned above.  
The bulk operation may be for MariaDB only. See [https://jira.mariadb.org/browse/MDEV-9114](https://jira.mariadb.org/browse/MDEV-9114)

I don't have a non-Rust front end handy, although I could write something in Python.  
The command line MySQL client doesn't support bulk mode INSERT operations; you have to explicitly put all the data in the SQL statement.

This can't be a unique problem. I mostly do graphics, not CRUD apps, so this area is new to me. It must be old to others.

---

<div class="post-metadata">

**Author:** ![jumpnbrownweasel](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/jumpnbrownweasel/32/17403_2.png) [@jumpnbrownweasel](https://users.rust-lang.org/u/jumpnbrownweasel)\
**Post date:** [March 27, 2026, 6:38pm UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/10 "2026-03-27T18:38:58Z")

</div>

> [@John\_Nagle](#):
>
> It's a slow shared server, but 17TPS? Come on.

It could be anywhere in the stack. One quick check is to measure ping times to the server, to at least rule out network issues.

---

<div class="post-metadata">

**Author:** ![John\_Nagle](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/john_nagle/32/17844_2.png) [@John\_Nagle](https://users.rust-lang.org/u/John_Nagle)\
**Post date:** [March 27, 2026, 7:11pm UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/11 "2026-03-27T19:11:43Z")

</div>

```rust
> ping -c 5 terrain.animats.info
PING terrain.animats.info (208.113.244.178) 56(84) bytes of data.
64 bytes from figueira.iad1-mysql-e2-6b.dreamhost.com (208.113.244.178): icmp_seq=1 ttl=47 time=64.1 ms
64 bytes from figueira.iad1-mysql-e2-6b.dreamhost.com (208.113.244.178): icmp_seq=2 ttl=47 time=64.0 ms
64 bytes from figueira.iad1-mysql-e2-6b.dreamhost.com (208.113.244.178): icmp_seq=3 ttl=47 time=64.0 ms
64 bytes from figueira.iad1-mysql-e2-6b.dreamhost.com (208.113.244.178): icmp_seq=4 ttl=47 time=64.3 ms
64 bytes from figueira.iad1-mysql-e2-6b.dreamhost.com (208.113.244.178): icmp_seq=5 ttl=47 time=64.1 ms

--- terrain.animats.info ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4006ms
rtt min/avg/max/mdev = 63.969/64.090/64.277/0.107 ms

```

64 ms round trip, or about 17 round trips per second. So this is what you'd expect if the "mysql" connector doesn't do bulk mode.

OK, so:

- MariaDB has support for bulk insert, and Rust "mysql" supports this, but MySQL does not. **exec\_bulk** isn't very "bulk" except for MariaDB. I'm stuck with MySQL 8.0 here.
- Rust "sqlx" has [QueryBuilder in sqlx - Rust](https://docs.rs/sqlx/latest/sqlx/struct.QueryBuilder.html) which can assemble an insert with multiple Values clauses, but it doesn't do all the escaping and sanitization needed for a safe INSERT; it just constructs a big string SQL statement with a huge VALUES clause. And it's the user's responsibility to make sure the statement isn't too long.
- Constructing a big SQL string with rows and rows of VALUE items using string operations and manual escaping directly is about equally easy as "sqlx". It kind of defeats the purpose of the "mysql" crate, with all its iterator and name interpolation features.

Well, now I understand what's wrong. Bleah.

---

<div class="post-metadata">

**Author:** ![jumpnbrownweasel](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/jumpnbrownweasel/32/17403_2.png) [@jumpnbrownweasel](https://users.rust-lang.org/u/jumpnbrownweasel)\
**Post date:** [March 27, 2026, 7:27pm UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/12 "2026-03-27T19:27:00Z")

</div>

> [@John\_Nagle](#):
>
> One giant VALUES clause would work for this test set, but the real data will have about 20,000 rows, which is too much for that approach.

Even if you only can send 1000 or even 100 values per request, this could increase throughput by orders of magnitude. Using VALUES is the recommended solution as far as I can tell.

---

<div class="post-metadata">

**Author:** ![John\_Nagle](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/john_nagle/32/17844_2.png) [@John\_Nagle](https://users.rust-lang.org/u/John_Nagle)\
**Post date:** [March 27, 2026, 7:35pm UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/13 "2026-03-27T19:35:00Z")

</div>

> [@jumpnbrownweasel](#):
>
> Using VALUES is the recommended solution as far as I can tell.

Yeah. I thought that **exec\_bulk** took care of that, but it doesn't. I'm amazed this isn't better supported.

---

<div class="post-metadata">

**Author:** ![John\_Nagle](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/john_nagle/32/17844_2.png) [@John\_Nagle](https://users.rust-lang.org/u/John_Nagle)\
**Post date:** [March 28, 2026, 3:02am UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/14 "2026-03-28T03:02:10Z")

</div>

OK, working on a workaround plan. I'd like to avoid my own string munging of MySQL values. That way lies SQL injection bugs.

Need a function to insert a variable-length list of values. Something like this:

```rust
/// My type to be inserted. Demo only.
struct MyValues {
    foo: i32,
    bar: bool,
    baz: String
}
/// Do the insert.
/// The basic question here is, having constructed a Vec of a Vec of mysql::Value,
/// how do I push it into MySQL? The crate has functions for constructing such a
/// type, but no indication of how to use it. This sketches out what I'd like to do.
/// But it probably won't work.
fn insert_vec_of_values(tx: &mut Transaction, values_vec: Vec<Vec<Values>>) -> Result<(), Error> {
    const INSERT_STMT: &str = r"INSERT (foo, bar, baz) into my_table VALUES (:values)";
    let params = params!{
        "values" => values_vec, // ***PROBABLY NOT ALLOWED***
    };
    tx.exec_drop(sql_cmd, &params)?; // do a multi-row insert.
}

/// Assemble a vector of values to insert
fn construct_vec_of_values(my_values: &[MyValues]) -> Result<Vec<Vec<Values>>, Error> {
    let mut values_vec = Vec::new();
   for p in &my_values {
       let row_params = params!(
           "foo" => p.foo,
           "bar" => p.bar,
           "baz" => p.baz.clone(), // it's a string, can't copy implicitly
      }
     values_vec.push(row_params.vec_of_values()?);
   }
   // so now we have a Vec of a Vec of "mysql" crate values. Is that what we want?
   Ok(vec_of_values)
}

/// Build and insert values
fn insert_my_values(tx: &mut Transaction, my_values: &[MyValues]) -> Result<(), Error> {
    insert_vec_of_values(tx, construct_vec_of_values(my_values)?)
}

```

---

<div class="post-metadata">

**Author:** ![John\_Nagle](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/john_nagle/32/17844_2.png) [@John\_Nagle](https://users.rust-lang.org/u/John_Nagle)\
**Post date:** [March 28, 2026, 6:20am UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/15 "2026-03-28T06:20:04Z")

</div>

It's clunky, but a Value can be converted to a string with

pub fn [as\_sql](https://docs.rs/mysql/latest/mysql/enum.Value.html#method.as_sql)(&self, no\_backslash\_escape: [bool](https://doc.rust-lang.org/nightly/std/primitive.bool.html)) -\> [String](https://doc.rust-lang.org/nightly/alloc/string/struct.String.html)

So I have to put in what's mostly binary numerical data, which is then converted to **mysql::Value** , which is then converted to SQL text syntax, which is then parsed and converted to binary SQL wire protocol.

Is this the way to do it?

---

<div class="post-metadata">

**Author:** ![John\_Nagle](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/john_nagle/32/17844_2.png) [@John\_Nagle](https://users.rust-lang.org/u/John_Nagle)\
**Post date:** [March 28, 2026, 7:46am UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/16 "2026-03-28T07:46:33Z")

</div>

If it doesn't work, get a bigger hammer. Process in chunks of 200 records, use the **params!** macro, then convert each param to **mysql::value** , then to an SQL string, then join the strings with commas, then append all this to the canned SQL command and shove that into MySQL. You know, all that stuff an ORM is supposed to do for you.

This takes \< 1 second, compared to the previous nice, clean, 26 second approach.

The **mysql** crate handles all the escaping, so this approach should be safe against SQL injection attacks.

```rust
    /// Build temporary table rows
    fn build_temporary_table_chunks(&self, tx: &mut Transaction) -> Result<(), Error> {
       const INSERT_INUSE_UUID_ROWS: &str = r"INSERT INTO uuids_in_use
            (region_loc_x, region_loc_y, region_size_x, region_size_y, asset_type, asset_uuid, asset_hash) VALUES
            ";
        const NAMED_PARAMETERS: [&str;7] = ["region_loc_x", "region_loc_y", "region_size_x", "region_size_y", "asset_type", "asset_uuid", "asset_hash"];
        let named_parameters: Vec<_> = NAMED_PARAMETERS.iter().map(|p| p.to_string().into_bytes()).collect();
        // Not too big; query size is limited to 32767 (?) bytes.
        const CHUNK_SIZE: usize = 200;
        let active_uuids = self.get_uuids_in_use(tx)?;
        log::info!("{} active UUIDs: {:?}", active_uuids.len(), &active_uuids[0..3.min(active_uuids.len())]);
        for active_uuid_chunk in active_uuids.chunks(CHUNK_SIZE) {
            log::debug!("Chunk with {} items", active_uuid_chunk.len());
            let mut value_strings = Vec::new();
            for p in active_uuid_chunk {
                let row_params = params!{
                    "region_loc_x" => p.region_loc[0],
                    "region_loc_y" => p.region_loc[1],
                    "region_size_x" => p.region_size[0],
                    "region_size_y" => p.region_size[1],
                    "asset_type" => p.asset_type.to_str().to_string(),
                    "asset_uuid" => p.asset_uuid.to_string(),
                    "asset_hash" => p.asset_hash.clone(),                    
                };
                // Make one row.
                let row_string: String = row_params.into_values(Some(&named_parameters))?
                    .into_iter()
                    .map(|v: mysql::Value| v.as_sql(false))
                    .collect::<Vec<_>>().join(",");
                 value_strings.push(format!("({})", row_string));
            }
            // All escaping was done above.
            // Make final SQL statement by concatenating query and values.
            let sql = INSERT_INUSE_UUID_ROWS.to_string() + value_strings.join(",\n").as_str();
            log::debug!("Query: {}", sql); // ***TEMP***
            // Actually do the insert of one chunk.            
            tx.query_drop(sql)?;           
        }
        Ok(())   
    }

```

---

<div class="post-metadata">

**Author:** ![SkiFire13](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/skifire13/32/17959_2.png) [@SkiFire13](https://users.rust-lang.org/u/SkiFire13)\
**Post date:** [March 28, 2026, 9:43am UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/17 "2026-03-28T09:43:33Z")

</div>

> [@John\_Nagle](#):
>
> Although the comments indicate it uses MySQL's bulk mode, what the code seems to do (look at the loop that begins at line 384) is iterate over "params" and do each substatement as a separate operation. Am I reading that right?

The [code](https://github.com/blackbeam/rust-mysql-simple/blob/08b7f90aec8586e1fc64a3a1fa9cb09bfdce98aa/src/conn/queryable.rs#L149) claims to checks first if the server supports MariaDb's `COM_STMT_BULK_EXECUTE` and if so uses that capability, otherwise it will fall back to running each statement individually.

> [@John\_Nagle](#):
>
> Rust "sqlx" has [QueryBuilder in sqlx - Rust](https://docs.rs/sqlx/latest/sqlx/struct.QueryBuilder.html) which can assemble an insert with multiple Values clauses, but it doesn't do all the escaping and sanitization needed for a safe INSERT

It seems you can just use `push_bind` to add binded values. That should have no escaping/sanitization needed, and the only issue remaining should be the size of the resulting statement or number of binded values.

---

<div class="post-metadata">

**Author:** ![John\_Nagle](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/john_nagle/32/17844_2.png) [@John\_Nagle](https://users.rust-lang.org/u/John_Nagle)\
**Post date:** [March 28, 2026, 6:31pm UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/18 "2026-03-28T18:31:38Z")

</div>

Proposed a change to the **mysql** crate to make exec\_batch actually do batching. See

> <https://github.com/blackbeam/rust-mysql-simple/issues/411>
>
> Unless the back end is MariaDB, \*\*exec\_batch\*\* just executes the same statement …over and over, with new parameters. There's no batching. Very slow. I had to work around this, \[here.\](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200) That code creates INSERT statements with multiple rows, with a few hundred rows per MySQL request. Speedup was about 30x. 
> 
> The MySQL crate could do this in \*\*exec\_batch\*\*, transparent to the user, roughly as follows:
> 
> \- Scan SQL string. Find VALUES clause. Extract row values part\` (:name1, :name2, ...) \`
> \- Generate rows of values, getting data from the iterator parameter to exec\_batch.
> \- Reassemble SQL statement with the VALUES clause now containing multiple rows. Submit to the database server.
> \- For large sets of values, submit to the server in chunks, keeping each request below the maximum SQL statement size.
> 
> This is good for 1 to 2 orders of magnitude performance on bulk INSERT operations.
> 
> (That's what I thought \*\*exec\_batch\*\* did, until I hit this performance bug and looked at the code.)

So I have a workaround, and have proposed a more permanent fix. Done here.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [June 26, 2026, 6:32pm UTC](https://users.rust-lang.org/t/really-slow-mysql-inserts/139200/19 "2026-06-26T18:32:23Z")

</div>

Closed on June 26, 2026, 6:32pm UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
