Search code examples
c#mysqlmax-allowed-packet

How can I query the MySQL Max_Allowed_Packet through c#?


I am trying to check the value of the max_allowed_packet size. This is my code:

public int MaxAllowedPacket()
{                
    var max = 0;
    using (var conn = new MySqlConnection(_ConnectionString))
    {
        var sql = conn.CreateCommand();
        sql.CommandText = "SHOW VARIABLES like 'max_allowed_packet'";

        try
        {
            conn.Open();
            var reader = sql.ExecuteReader();
            // not sure where to go from here
        }
        catch (Exception ex)
        {
            // I've got some logging here
        }
    }
    return max;
}

I'm suspecting the format of the query or the execution is wrong because my result is always

-1

EDIT:

I have edited the code to use sql.ExecuteReader() but the result is now:

"Enumeration yielded no results".


Solution

  • Eventually figured it out myself, and thought to post it here, before this gets downvoted even more...

    var reader = sql.ExecuteReader();
    reader.Read();
    max = reader.GetInt32(1);
    

    It's best to put some try catches around and you can optionally query the first field through reader.GetString(0), which should return "max_allowed_packet".