C# INSERT fails with 'Fatal error encountered during command execution'
Fatal error encountered during command execution.Short answer
A fatal error during command execution means the connection broke while the INSERT was in flight. The server usually closed it: the statement was bigger than max_allowed_packet, or the connection sat idle past wait_timeout. A connection shared by two operations at once breaks it from the client side too.
Fix it fast
1Find out which cause you have
Read the two server limits that most often close a connection during a write.
SHOW VARIABLES LIKE 'max_allowed_packet'; SHOW VARIABLES LIKE 'wait_timeout';2Match what you see, then jump to its fix
- 1
Only big inserts fail: a large blob, long text, or one INSERT with thousands of rowsThe INSERT is larger than max_allowed_packetFix - 2
The first write after a quiet period fails, then the next one worksThe server closed an idle pooled connectionFix - 3
Errors under parallel load, or an INSERT inside a loop that is still reading from the same connectionTwo operations used the same connection at the same timeFix
- 1
What does the error look like?
Fatal error encountered during command execution.MySql.Data.MySqlClient.MySqlException: Fatal error encountered during command execution
Cause 1 of 3
The INSERT is larger than max_allowed_packet
1Check
If mysqld receives a packet that is too large it treats the client as broken and closes the connection. Compare your largest statement or row with the server value above.
SHOW VARIABLES LIKE 'max_allowed_packet';2Fix
Raise the limit on the server, and split very large multi-row INSERT statements into smaller batches, because all rows in one statement travel in one request.
SET GLOBAL max_allowed_packet = 134217728;
-- or in my.cnf under [mysqld]:
-- max_allowed_packet = 128M3Verify
Open a new connection and read the value; the setting applies to new connections only.
SHOW VARIABLES LIKE 'max_allowed_packet';Confirmed by dev.mysql.com
Cause 2 of 3
The server closed an idle pooled connection
1Check
The server closes idle connections after wait_timeout seconds (28800, eight hours, is the documented default). A pooled connection that lives longer than the limit set on your server is dead when reused.
SHOW VARIABLES LIKE 'wait_timeout';2Fix
Raise wait_timeout, or make the pool retire connections sooner with Connection Lifetime so they never outlive the server limit.
Server=db.example.com;Database=app;User ID=app;Password=...;Connection Lifetime=3003Verify
Run the same insert after an idle period longer than before.
dotnet runConfirmed by mysqlconnector.net
Cause 3 of 3
Two operations used the same connection at the same time
1Check
A MySqlConnection can run only one operation at a time. Parallel ExecuteAsync calls, a command issued inside a reader.Read() loop, or a Dispose while an operation runs all break it.
grep -R -n "Task.WhenAll" --include=*.cs .2Fix
Give each parallel task its own connection, or await operations one after another. Finish and close a reader before running another command, and use using or await using for the connection.
await using var conn = new MySqlConnection(connectionString);
await conn.OpenAsync();
await using var cmd = new MySqlCommand("INSERT INTO items (name) VALUES (@n)", conn);
cmd.Parameters.AddWithValue("@n", name);
await cmd.ExecuteNonQueryAsync();3Verify
Repeat the load that failed before.
dotnet testConfirmed by mysqlconnector.net
How do I stop it coming back?
- Insert large data in batches, not in one giant statement.
- Create a connection per operation and let pooling reuse it.
- Know the max_allowed_packet and wait_timeout values on every server you deploy to.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Databases
EF Core logs 'An error occurred using the connection to database' with MySQL
Can't connect to MySQL server on 'host_name' (111)
This EF Core message is only a wrapper.
3 causes, each with a fixDatabases
DbContextOptionsBuilder has no UseMySql method
Cannot find the UseMysql method on DbContextOptions
UseMySql comes from a provider package, not from EF Core itself.
3 causes, each with a fixDatabases
There is already an open DataReader on the MySQL connection
The error appears inside a while (reader.Read()) loop
One MySQL connection runs one operation at a time.
3 causes, each with a fixDatabases
MySqlException: Timeout expired in a .NET app
MySql.Data.MySqlClient.MySqlException: Timeout expired
Timeout expired means a wait ended before it finished.
3 causes, each with a fixDatabases
C# cannot reach MySQL: connection attempt failed, no response in time
System.Net.Sockets.SocketException (10060)
SocketError 10060 means the connection attempt timed out, or the host did not respond.
3 causes, each with a fixDatabases
MySqlException: unable to connect to any of the specified MySQL hosts
Can't connect to MySQL server on 'host' (10061)
The connector could not open a TCP connection to the host and port in your connection string.
4 causes, each with a fix