jokul
jokul

Reputation: 1339

MySqlCommand.ExecuteScalar() not returning anything

When I run the following code:

query = "select count(*) from table where name = '?name'";
MySqlConnection connection = 
  new MySqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ToString());
connection.Open();
MySqlCommand command = new MySqlCommand(query,connection);
command.Parameters.Add("?name", name);
Int32 number = command.ExecuteScalar();

number is always zero, even when cast to an int.

I have tried converting it to int64, no dice. I have tried command.Prepare(). I have tried using Convert.ToInt32() and every other variation. I have tried just about everything under the sun including quoting verbatim what this suggests and I get no dice. Trying to cast the object as an integer, as a long, as an int32, none of this seems to work. These results are always 0 or cause a MySQL error.

EDIT: Stack overflow will not format that code properly in code tags, i apologize

Upvotes: 2

Views: 6951

Answers (1)

John Woo
John Woo

Reputation: 263723

The reason for that is because the parameter is enclose with single quote thus making it a string. Remove it and it will work,

query = "select count(*) from table where name = @name";
MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ToString());
connection.Open();
MySqlCommand command = new MySqlCommand(query,connection);
command.Parameters.Add("@name", name);

for better code,

  • use using for proper object disposal
  • using try-catch block for proper handling of exceptions

code snippet,

query = "select count(*) from table where name = @name";
string connString =ConfigurationManager.ConnectionStrings["mydb"].ToString();
using(MySqlConnection connection = new MySqlConnection(connString))
{
    using(MySqlCommand command = new MySqlCommand(query, connection))
    {
        command.Parameters.Add("@name", name);
        try
        {
            connection.Open();
            // other codes
        }
        catch(MySqlException ex)
        {
            // do somthing with the exception
            // don't hide it
        }
    }
}

Upvotes: 5

Related Questions