What is the correct way to convert between a MySql bool and a C# bool?

Viewed 501

I'm struggling to understand the correct way to convert between a MySql bool and a C# bool.

And it doesn't help that code which was working with MySql.Data v8.0.21 no longer works with v8.0.22.

In the code below, why do I (now) need to specify the MySqlDbType as Byte? Surely Bit is a better presentation of a boolean value?

And why is the type of cmd.Parameters["success"].Value either ulong or sbyte? Shouldn't it be bool?

[TestFixture]
public class MySqlTests
{
    private const string connString = "server=localhost;database=mysql;user=root;password=";

    [SetUp]
    public void SetUp()
    {
        using var cnn = new MySqlConnection(connString);
        cnn.Open();
        var cmd = cnn.CreateCommand();
        cmd.CommandText = @"
            DROP PROCEDURE IF EXISTS Test;
            CREATE PROCEDURE Test (OUT success BOOL)
            BEGIN
                SET success = true;
            END
        ";
        cmd.ExecuteNonQuery();
    }

    [TestCase(MySqlDbType.Bit, typeof(ulong))] // succeeds with MySql.Data v8.0.21, fails with v8.0.22
    [TestCase(MySqlDbType.Byte, typeof(sbyte))]
    public void Test(MySqlDbType mySqlDbType, Type expectedType)
    {
        using var cnn = new MySqlConnection(connString);
        cnn.Open();
        var cmd = cnn.CreateCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "Test";
        cmd.Parameters.Add(new MySqlParameter("success", mySqlDbType) {Direction = ParameterDirection.Output});
        cmd.ExecuteNonQuery();
        var success = cmd.Parameters["success"].Value;
        Assert.AreEqual(expectedType, success.GetType(), "Unexpected Type");
    }
}

If it matters, I'm running MySql:5.7

1 Answers

Mysql does not have a real boolean data type, bool is just an alias of tinyint. Tinyint is stored on 1 byte, so it maps to C#'s sbyte data type.

Why different versions of mysql data handle this mapping differently, I cannot tell, you need to ask the developers.

Related