Svenmarim
Svenmarim

Reputation: 3735

C# MySqlCommand parameter with value of DBNull.Value not working

Why is the value of DBNull.Value not working in the following code? I keep getting false as return value, while i am sure there is a record that matches.

(machineNumber has indeed the value of "b", so that is not the issue)

MySqlCommand cmd = new MySqlCommand("SELECT * FROM `sparter` WHERE `id` = @machineNumber AND `account_id` = @null", conn);

            cmd.Parameters.AddWithValue("@machineNumber", machineNumber);
            cmd.Parameters.AddWithValue("@null", DBNull.Value);

            using (var reader = cmd.ExecuteReader())
            {
                return reader.read();
            }

While this query IS working in MySqlWorkbench:

SELECT * FROM `sparter` WHERE `id` = "b" AND `account_id` IS NULL

Upvotes: 1

Views: 344

Answers (1)

Antoine V
Antoine V

Reputation: 7204

In fact, in MySQL use = or != null don't work. Use IS NULL or IS NOT NULL.

Can you try with this:

MySqlCommand cmd = new MySqlCommand("SELECT * 
                                     FROM `sparter`
                                     WHERE `id` = @machineNumber AND `account_id` is @null", conn);

Upvotes: 2

Related Questions