MySqlException: Timeout expired - Increasing Connection Timeout Has Had No Effect
Asked Answered
L

3

12

I have a query that is taking longer to execute as the database increases in size. The query is optimized and necessary, but my C# Console Application has recently been giving me this error:

Unhandled Exception: MySql.Data.MySqlClient.MySqlException: Timeout expired.

Increasing the connection time out in the connection string doesn't help; I increased it from

Connect Timeout=28800

to

Connect Timeout=128800

but I'm still getting the error despite this change.

If I run the query from MySQL workbench it only take about 10 seconds, so I'm not sure how to prevent this Unhandled Exception.

Are there other things, besides "the time a query takes", that can produce this exception?

Lakeshialakey answered 16/7, 2012 at 17:55 Comment(4)
Change the CommandTimeout not the ConnectionTimeout.Unplaced
The CommandTimeout not the ConnectionTimeout.Unplaced
public static string ConnectionString = "server=192.168.1.2;user=user1;database=database1;port=3306;password=testPW;Pooling=true;Connect Timeout=28800;Command Timeout=28800"; I'm still testing.Lakeshialakey
Thanks Tim! I haven't experience the timeout since I set the Command Timeout, as shown in my connection string above.Lakeshialakey
F
23

I've had this problem before. ConnectTimeout property only applies to time outs that occur when connecting to the database, not for queries.

CommandTimeout however specifies how long it should wait for the query to return. I believe the default is 30 seconds. Double check the documentation for your MySql library, but for SqlCommand the CommandTimeout is in Seconds not milliseconds.

Flipflop answered 16/7, 2012 at 19:39 Comment(1)
In MySQL is also seconds. also - 0 is no timeout.Kaitlynkaitlynn
N
4

You can also try adding "default command timeout=360" in your connection string; eg

Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;default command timeout=20;

This option is available from Connector/NET version 5.1.4.

[I lifted this from connectionstrings.com/mysql/

Nahtanha answered 2/9, 2014 at 23:11 Comment(0)
J
3

If you can show us your method, we can help find the bugs.

If history (and SO ) has taught me anything, its

"You better be using Paramaterized SQL statements before posting any code" 

If you are unsure on how to use parameterized commands here is an example ( taken from one of the answers where I didn't use parameterized SQL )

var command = new MySqlCommand(
    "SELECT * FROM tblPerson WHERE LastName = @Name AND Height > @Height AND BirthDate < @BirthDate", connection);

command.Parameters.AddWithValue("@Name", lastname);
command.Parameters.AddWithValue("@Height", height);
command.Parameters.AddWithValue("@Name", birthDate);

Try that if you haven't already and post some code :)

Jamille answered 16/7, 2012 at 18:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.